我一直试图想出一种方法来根据下面的代码获取所有正输入数字的总和
#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);
}
但是我什么都想不出来,因为我对编程还很陌生。任何帮助表示赞赏!
答案 0 :(得分:2)
正如评论中提到的,您是计数而不是求和,但是作为新程序员,您可以考虑检查整数是否为正的条件 - 例如 {{ 1}}
所以我可以建议您的 myFunction 可以是这样的:
if (num1 > 0) { // here you add sum or count depends what you want }
我希望它能让你清楚!
答案 1 :(得分:0)
您可以使用条件语句来减少代码并使其更简洁
#include <iostream>
using namespace std;
void myFunction(int num1, int num2, int num3) {
int x= (num1>=0?1:0) + (num2>=0?1:0) + (num3>=0?1:0);
cout << "From the entered numbers " << x << " of them are positive numbers";
int sum= (num1>0?num1:0) + (num2>0?num2:0) + (num3>0?num3:0);
cout<<sum;
}
int main() {
int y1, y2, y3;
cout << "Enter numbers: ";
cin >> y1 >> y2 >> y3;
myFunction(y1, y2, y3);
}