V
V
Vladimir Krasnopolsky2020-12-03 09:14:25
C++ / C#
Vladimir Krasnopolsky, 2020-12-03 09:14:25

Why does c++ count incorrectly?

Hi when i run the code:

#include <iostream>
using namespace std;
int main() {
   int s, i;
   s = 8;
    for (i = 2; i <= 8; i++)
    {
        s = s + 8;
        cout<<s;
    }
}

compiler outputs 16243240485664 not 64

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
DeOxygen, 2020-12-03
@4atty

Because you're outputting each step of the loop. Putting std::cout outside the loop

#include <iostream>
using namespace std;
int main() {
   int s, i;
   s = 8;
    for (i = 2; i <= 8; i++)
    {
        s = s + 8;  
    }
 cout<<s;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question