0

A question about C++

I have just made a simple code about adding all the numbers that user entered; how do i make it to subtract the first number with the other numbers that user have entered; Below is my code; #include <iostream> using namespace std; int main(){ int a; int x; int y; int total; cout << "What do you want to do with these numbers" << endl; // sum = 1, sub = 2, multi = 3, div =4 cin >> a; cout << "How many number do you have to perform?" << endl; cin >> x; if ( a == 1) { for (int z = 1; z <= x; z++) { cin >> y; total += y; } } if ( a == 2) { for (int z = 1; z <= x; z++) { cin >> y; total -= y; } } cout << total; return 0; }

29th Nov 2020, 11:47 PM
J3W 26 林珉佑 Lim Ming You
J3W 26 林珉佑 Lim Ming You - avatar
2 Respuestas
0
You can: cin >> y; total=y; just before the loop starts and make the condition z<x
29th Nov 2020, 11:59 PM
Angelo
Angelo - avatar
0
As Stefano said, you have to set total=y before to enter the loop. And the same thing for division. For the addition you need to set total to zero otherwise the sum starts from a garbage value. And for multiplication you need to set the total to 1 so that in the loop you can do total*=y;
30th Nov 2020, 12:38 AM
Davide
Davide - avatar