简体   繁体   English

只有负数正确相加

[英]Only negative numbers adding correctly

So I'm trying to write a program that will read in ten whole numbers and outputs the sum of all numbers greater than zero, the sum of all numbers less than zero, and the sum of all numbers, whether positive, negative, or zero.所以我正在尝试编写一个程序,该程序将读取十个整数并输出所有大于零的数字的总和、所有小于零的数字的总和以及所有数字的总和,无论是正数、负数还是零. Currently only the total sum and negative sum is adding correctly.目前只有总和和负和正确相加。 My positive sum is always 1 or 0. Any tips to get me in the right direction would help.我的正和总是 1 或 0。任何让我朝着正确方向前进的提示都会有所帮助。

Current Code:当前代码:

#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;

}

After entering all N s and when entring to the loop, you have only the last N .输入所有N后并进入循环时,您只有最后一个N because after assigning the first number to N you don't process the value but you assigning the next value to N again after asking the user to enter it and so on.因为在将第一个数字分配给N您不处理该值,而是在要求用户输入后再次将下一个值分配给N ,依此类推。 Use something like the following使用类似以下内容

#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;

}

And see Why is "using namespace std;"并查看为什么是“使用命名空间 std;” considered bad practice? 被认为是不好的做法?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM