+ 3

Why does it reiterate my previous input in the while loop when I only input once or twice.

if I input ' 0 0 5' it compiles it to 15. why not 5? https://code.sololearn.com/c1h1iH5jxg0j/?ref=app

16th Dec 2017, 6:22 AM
Sammy
Sammy - avatar
7 odpowiedzi
+ 1
so basically it is the problem with cin it is considering last value for all other iteration. 0 0 5 is interprited as 0 0 5 5 5 0 5 0 is interprited as 0 5 0 0 0 so if you have not given enough cin values then it will consider last cin values for others. so if give input 0 5 0 then also you will get output as 5.
16th Dec 2017, 6:25 PM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar
+ 2
can you please put sample code?
16th Dec 2017, 7:00 AM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar
+ 2
ooh I am sorry, that's a mistake
16th Dec 2017, 5:14 PM
Sammy
Sammy - avatar
+ 2
thank you Great Saga . you've been helpful
16th Dec 2017, 11:20 PM
Sammy
Sammy - avatar
+ 1
I have done that @ Saga.. thanks for informing.
16th Dec 2017, 5:16 PM
Sammy
Sammy - avatar
+ 1
hi, problem is with your input ... if you are giving input like this 0 0 5 then it will take input as 0 0 5 5 5 so you get output as 15. if u give input like 0 0 0 0 5 then you will get output 5. for proof please run below code and verify the cout prints... #include <iostream> using namespace std; int main() { int num = 1; int number; int total = 0; while (num <= 5) { cin >> number; cout<<" total = " << total << " number = "<<number<<endl; total += number; num++; } cout << "final ="<<total << endl; return 0; }
16th Dec 2017, 6:17 PM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar
+ 1
@Sammy, Always wel come.
17th Dec 2017, 2:32 AM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar