c++ - 我如何得到所有积极输入的数字的总和
问题描述
我一直在尝试想出一种方法来根据下面的代码获取所有积极输入的数字的总和
#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);
}
但是我什么都想不出来,因为我对编程很陌生。任何帮助表示赞赏!
解决方案
正如评论中提到的那样,您计算的不是求和,但是作为新程序员,您可以考虑检查整数是否为正的条件-例如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; }
我希望它能让你清楚!
推荐阅读
- string - 我编写了一个函数来将字符串分成由 $ 分隔的部分现在我需要使用 select from 来访问它,但出现错误
- javascript - 当数据库中没有数据时,Select2 AJAX 不显示“未找到数据”,而是显示搜索参数作为选择选项
- sql - 优化 postgresql 查询
- c++ - WinUsb with C++ Builder 10.3 社区版
- html - 没有从 soup.findAll() 获得所有结果
- amp-html - 带有 amp-auto-ads 的 Adsense 覆盖广告?
- google-cloud-dataflow - 当新数据到达 Bigquery 时触发数据流作业
- sql - 如何使用最右边的表过滤多对多左连接?
- javascript - 在 Bootstrap Carousel 中放置 DIV 容器
- udeploy - 我正在从 teamcity 触发构建,版本会自动导入 UCD,但没有发生自动部署