c++ - 显示用户输入的大于 50 的平均数和所有可被 3 整除的数字的乘积

标签 c++

我需要编写一个程序来获取一系列数字,直到输入 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/

相关文章:

c++ - 对右值使用移动赋值运算符时的异常

c++ - 这个二维数组初始化是个坏主意吗?

c++ - 这个 cin.getline() 行为是什么?

c++ - 不使用动态内存分配的 Pimpl 习惯用法

c++ - 自定义类型的 Qml 属性

c++ - ClassName objectName(4); 有什么区别?和 ClassName objectName = 4;

c++ - 设置 Boost 正则表达式语言环境?

c++ - 同名类之间的共享 vtables : call to virtual method crashes when casting to base type

c++ - 如何将 "mean_file_proto"读入 OpenCV Mat 以便从均值中减去图像以用于 Caffe 模型?

c++ - LLVM 将函数调用插入另一个函数