首页 > 解决方案 > 我如何得到所有积极输入的数字的总和

问题描述

我一直在尝试想出一种方法来根据下面的代码获取所有积极输入的数字的总和

#include <iostream>
using namespace std;

void myFunction(int num1, int num2, int num3) {
    int x;
    x = 0;
    if (num1 > 0) {
        x++;
    }
    if (num2 > 0) {
        x++;
    }
    if (num3 > 0) {
        x++;
    }
    cout << "From the entered numbers " << x << " of them are positive numbers";
}


int main() {
    
    int y1, y2, y3;
    
    cout << "Enter numbers: ";
                                                                   
    cin >> y1 >> y2 >> y3;
    
    myFunction(y1, y2, y3);                   
    
}

但是我什么都想不出来,因为我对编程很陌生。任何帮助表示赞赏!

标签: c++

解决方案


正如评论中提到的那样,您计算的不是求和,但是作为新程序员,您可以考虑检查整数是否为正的条件-例如if (num1 > 0) { // here you add sum or count depends what you want }

所以我可以建议你的myFunction可以是:

void myFunction(int num1, int num2, int num3) {
int x, positive_sum;
x = 0, positive_sum = 0;
if (num1 > 0) {
    // here we deal with positive
    x++;
    positive_sum += num1;
}
if (num2 > 0) {
    x++;
    positive_sum += num2;
}
if (num3 > 0) {
    x++;
    positive_sum += num3;
}
cout << "From the entered numbers " << x << " of them are positive numbers"<<endl;
cout << "Sum of these " << x << " numbers is " << positive_sum << endl; }

我希望它能让你清楚!


推荐阅读