[英]C++ User enters x amount of inputs than sum them
I am trying to write a program that asks the user to enter how many integers they would like to sum then asks them to input those integers and sum them.我正在尝试编写一个程序,要求用户输入他们想要求和的整数数量,然后要求他们输入这些整数并对它们求和。
int main() {
char choice;
do {
int input, sum, num1, num2;
cout << endl;
cout << "How many integer values would you like to sum? ";
cin >> input;
for (int i = 0; i < input; i++) {
cout << "Enter integer ";
cin >> num1;
}
sum = num1;
cout << "Do you want to go again (y/n)? ";
cin >> choice;
} while (choice == 'y');
cout << endl;
return 0;
}
This is what I am trying to achieve with my program:这就是我试图通过我的程序实现的目标:
How many numbers are you going to enter? 5
Enter data: -5
Enter data: 2
Enter data: 3
Enter data: 6
Enter data: 0
The sum is 6
You just have to add the value of input integers into sum every time in the for loop using sum += num
or sum = sum + num
both works in the same way.您只需要每次在 for 循环中使用sum += num
或sum = sum + num
都以相同的方式将输入整数的值添加到 sum 中。
char choice;
do {
int input, sum, num;
cout << endl;
cout << "How many integer values would you like to sum? ";
cin >> input;
for (int i = 0; i < input; i++) {
cout << "Enter integer ";
cin >> num;
sum += num;
}
cout << "Do you want to go again (y/n)? ";
cin >> choice;
} while (choice == 'y' || choice == 'Y');
cout << endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.