+ 1

C++. Pls help me

How can i create a program that will accept input values while the input is not equal to zero.

25th Aug 2019, 11:31 AM
Jhune Belardo
Jhune Belardo - avatar
3 Respostas
+ 4
You will need a while loop, some number type variable, cin and booleans. It's all in the tutorial you're studying. Wanna show us your attempt?
25th Aug 2019, 12:15 PM
HonFu
HonFu - avatar
+ 1
i dont know why the input always infinite #include <iostream> using namespace std; main(){ int number,counter=0,sum=0,average; while(number!=0){ cout << "enter a number: "; cin >> number; sum+=number; if(number!=0) counter++; } average=sum/counter; cout << endl << endl << "the sum of all input numbers is: " << sum; cout << endl << "the average of all input numbers is: " << average;}
26th Aug 2019, 12:59 PM
Jhune Belardo
Jhune Belardo - avatar
0
I would change the code slightly like this: int number=0,counter=0,sum=0,average=0; do{ cout << "enter a number: "; cin >> number; sum+=number; if(number!=0) counter++; }while(number!=0); if(counter) average=sum/counter; I set number and average to zero to begin with, so that you don't get an error if you just hit return, and a valid result. To make that work, I have chosen the do while loop so that it runs at least once anyway. Look at the condition if(counter): It calculates the average only if there's a counter. Because otherwise you divide by zero which doesn't work. I would further recommend to use the type double for number, sum and average, because otherwise everything will be rounded down to an integer.
26th Aug 2019, 2:01 PM
HonFu
HonFu - avatar