#include <iostream>
int main()
{
int cnt = 0, sum = 0, value = 0;
std::cout << "Please enter a set of numbers and then press ctrl+z and ENTER to add the numbers that you entered" << std::endl;
if (cnt = value)
++cnt;
while (std::cin >> value)
sum += value;
std::cout << "the sum is: " << sum << std::endl;
std::cout << "the amount of numbers you entered are: " << cnt << std::endl;
return 0;
}
我的 if 语句是错误的,并且没有计算用户输入值的整数数量。
如何让程序计算用户使用循环输入的整数数量?
最佳答案
解决方案说明
为了计算所提供的整数的数量,只需在给出新输入时将 1 添加到 cnt 即可。 (请参阅下面带有//** 注释的行)。
此外,不需要在开始时进行 cnt==value 检查(并且缺少一个“=”字符)。
更新代码
总而言之,您的代码应更改如下:
#include <iostream>
int main()
{
int cnt = 0, sum = 0, value = 0;
std::cout << "Please enter a set of numbers and then press ctrl+z and ENTER to add the numbers that you entered" << std::endl;
while (std::cin >> value)
{
sum += value;
cnt++; //**
}
std::cout << "the sum is: " << sum << std::endl;
std::cout << "the amount of numbers you entered are: " << cnt << std::endl;
return 0;
}
关于c++ - 计算用户使用循环输入的整数数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44094127/