我需要编写一个程序来获取一系列数字,直到输入 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);
最佳答案
您应该将 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;
}
否则程序会在这种情况下崩溃。
关于c++ - 显示用户输入的大于 50 的平均数和所有可被 3 整除的数字的乘积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55588596/