我需要编写一个程序,该程序将获得一系列数字,直到输入0。然后程序 显示大于50的所有数字的平均值以及所有数字的乘积 被3整除。
我已经可以得到平均数,但是当我输入的数字少于50时,程序中断了,而且我也无法获得被3整除的数的乘积。
#include <iostream>
using namespace std;
int main()
{
int total=0, result,num, inputCount=0, product = 1;
double average;
do{
cout << "Input numbers : " << endl;
cin >> num;
if(num>50){
inputCount++;
total = total+num;
}
}
while(num!=0);
cout<<"Average of numbers greater than 50 is ";
cout<<total/inputCount;
if(num % 3 == 0)
{
num*=num;
cout<< endl << "Product of all numbers divisible by 3 is " << num <<endl;
}
system("pause");
return 0;
}
我希望结果将是:
Input num : 90
Input num : 9
Input num : 0
Average of numbers greater than 50 is : 90
Product of all numbers divisible by 3 is : 810
由于用户输入了90、9和0,因此当输入0时,程序停止获取输入,然后大于50的平均值为90,因为90是唯一大于50且大于等于90和9的整数乘以3,所以90 * 9 =810。但是我得到的实际输出是
Average of numbers greater than 50 is : 90
Product of all numbers divisible by 3 is : 0
我尝试执行以下操作,但是当我输入0时,它也在循环中成倍增加。如何防止这种情况发生?
do{
cout << "Input numbers : " << endl; cin >> num;
if(num>50){ inputCount++; total = total+num; }
if(num % 3 == 0) { product = product * num; }
cout<< endl << "Product of all numbers divisible by 3 is " << product <<endl;
} while(num!=0);
答案 0 :(得分:0)
您应将if (num % 3 == 0
移入循环。
if (num > 50) {
inputCount++;
total = total + num;
}
if (num % 3 == 0 && num > 0)
{
product *= num;
}
还请注意&& num > 0
,因为0
也可以被3
整除,并且您想忽略这一点,否则您的产品将是0
。另外,您可以在执行这些检查之前将循环更改为在0
上中止。在循环之外,您应该只具有输出:
std::cout << "Product of all numbers divisible by 3 is " << product << std::endl;
作为旁注,我建议处理未输入大于50的数字的情况:
if (inputCount > 0) {
std::cout << "Average of numbers greater than 50 is " << total / inputCount << std::endl;
}
else {
std::cout << "No number greater than 50 was entered." << std::endl;
}
否则,程序会在发生这种情况时崩溃。