只有负数可以正确添加

时间:2020-09-15 00:25:18

标签: c++

因此,我正在尝试编写一个程序,该程序将读取十个整数并输出大于零的所有数字的总和,小于零的所有数字的总和, 以及所有数字的总和,无论是正数,负数还是零。 当前只有正确的总和和负的总和。我的正数总为1或0。任何使我朝正确方向发展的技巧都将有所帮助。

当前代码:

#include <iostream>
using namespace std;

int main()
{
int N = 0;
int sum = 0;
int positiveSum = 0;
int negativeSum = 0;

cout << "Number 1" << endl;
cin >> N;
cout << "Number 2" << endl;
cin >> N;
cout << "Number 3" << endl;
cin >> N;
cout << "Number 4" << endl;
cin >> N;
cout << "Number 5" << endl;
cin >> N;
cout << "Number 6" << endl;
cin >> N;
cout << "Number 7" << endl;
cin >> N;
cout << "Number 8" << endl;
cin >> N;
cout << "Number 9" << endl;
cin >> N;
cout << "Number 10" << endl;
cin >> N;

for(int i=0;i<10;i++)
 {
    if (N >= 0 )
    {
      positiveSum += N;
    }
    else
    {
        negativeSum += N;
    }
 }
    sum = positiveSum + negativeSum;
       cout << "The positive sum is= " << positiveSum << endl;
       cout << "the negative sum is= " << negativeSum << endl;
       cout << "The total sum is= " << sum << endl;

return 0;

}

1 个答案:

答案 0 :(得分:2)

输入所有N后,进入循环时,只有最后一个N。因为在将第一个数字分配给N之后,您不会处理该值,而是在要求用户输入后再将下一个值分配给N,依此类推。使用类似以下的内容

#include <iostream>

int main()
{
    int N = 0;
    int sum = 0;
    int positiveSum = 0;
    int negativeSum = 0;
    
    for(int i=0;i<10;i++)
    {
        std::cout << "Number "<<i + 1<< std::endl;
        std::cin >> N;
        
        if (N >= 0 )
        {
            positiveSum += N;
        }
        else
        {
            negativeSum += N;
        }
    }
    sum = positiveSum + negativeSum;
    std::cout << "The positive sum is= " << positiveSum << std::endl;
    std::cout << "the negative sum is= " << negativeSum << std::endl;
    std::cout << "The total sum is= " << sum << std::endl;

    return 0;

}

然后查看Why is "using namespace std;" considered bad practice?