+ 1

What's the problem?

#include <iostream> using namespace std; int main() { int a=0; int b[3]; cin>> b[0]>>b[1]>>b[2]; cout<< "Sum of all digits:"<< endl; for(int x=0 ; x>3 ; x++){ cout<<a+=b[x]; cout<<endl; } return 0; }

29th Mar 2020, 11:35 AM
Manas Negi
Manas Negi - avatar
8 Respostas
+ 1
what you have done will print the sum at each step, if you want to print just the total sum use this instead : #include <iostream> using namespace std; int main() { int a=0; int b[3]; cin>> b[0]>>b[1]>>b[2]; cout<< "Sum of all digits: "; for(int x=0 ; x<3 ; x++){ a+=b[x]; } cout <<a<<endl; return 0; } I just moved the cout out of the loop.
29th Mar 2020, 4:21 PM
John Robotane
John Robotane - avatar
+ 1
the for loop have a problem, it should be: for (int x=0; x<3;x++)
29th Mar 2020, 12:58 PM
John Robotane
John Robotane - avatar
+ 1
Super
31st Mar 2020, 5:19 AM
Mr.Madhiuki
Mr.Madhiuki - avatar
0
The ">>" operator used with std::cout has precedence over the "+=" operator, thus the line cout << a += b[ x ]; is interpreted as printing 'a' and then adding the value of "b[ x ]" to the output stream, which is not possible. Wrapping the assignment in parentheses should fix this problem, i.e. cout << ( a += b[ x ] );
29th Mar 2020, 12:11 PM
Shadow
Shadow - avatar
0
Sagar Thapaliya The code that is currently in the thread's description fails to compile due to what I said earlier, you can try it yourself.
29th Mar 2020, 12:50 PM
Shadow
Shadow - avatar
0
The answer by Shadow was appropriate ! Answer by John Robotane was also correct but it didn't worked after it too.
29th Mar 2020, 3:51 PM
Manas Negi
Manas Negi - avatar
0
John Robotane Thanks man!
29th Mar 2020, 5:41 PM
Manas Negi
Manas Negi - avatar
0
x < 3
31st Mar 2020, 5:40 AM
Thiên An
Thiên An - avatar