0

I don't know why the variable take the number 16, I want to know why

I have this code in C ++ and forget put variable to the number then when I run the code don't have problem but the output is 95 and can get the reason is the variable number take 16. I want to know what happanned #include <iostream> using namespace std; int main() { int num = 1; //Esto es un contador int number; //Esto es un variable de entrada int total = 0; //Esto es un acumuludor while (num<= 5) { //Esto es un ciclo number++; total += number; // Esto es igual a total= total + number num ++; } cout << total << endl; return 0; }

15th Oct 2020, 3:45 PM
Kvothe Dixon
Kvothe Dixon - avatar
3 Antworten
+ 2
See how loop working do dry run how values are changing . You can understood easily i u will calculate itself.
15th Oct 2020, 5:04 PM
A S Raghuvanshi
A S Raghuvanshi - avatar
0
It is 15 not 16 you added 1+2+3+4+5 try to use cout inside the loop to print number for each ciclo as i do here https://code.sololearn.com/cjdpInJCZ6jX/?ref=app
15th Oct 2020, 4:37 PM
HBhZ_C
HBhZ_C - avatar
0
It's a very bad thing to use the variable "number" without initializing a value to it (because it is a local variable, not global, global variables will be defaulted to 0).
17th Oct 2020, 2:20 AM
LastSecond959
LastSecond959 - avatar