简体   繁体   中英

Adding integers with c++

I am trying to write a program in c++ that allows you to enter 10 numbers and receive the sum of those numbers using a for loop. However, I am encountering a problem where I am not getting the added integers and instead getting the sum of the last 2 numbers.

#include <iostream>
using namespace std;

int main ()
{
    int i;
    int number;

    for(i; i < 10; i++)
    {
        cout << "enter a number" << endl;
        cin >> number;
        if( i < 10)
            number+= number;
    }

    cout << number;
    return 0;
}

1) You never initialize i , you should do so in the for loop.

for(int i=0; i < 10; ++i)

You also don't need:

if( i < 10 )

because based on your for loop conditions, this can never be false .

2) You also need to initialize number .

int number = 0;

3) You shouldn't cin directly to number or you will replace the total every single time. You could do this in your for loop for example.

int temp = 0;
cin >> temp;
number += temp;

Summary If you correct the above three issues, the modified code would look like this:

int main ()
{
    int number = 0;

    for(int i=0; i < 10; ++i)
    {
        cout << "enter a number" << endl;
        int temp = 0;
        cin >> temp;
        number += temp;
    }

    cout << number;
    return 0;
}

When you write cin >> number; you are replacing your sum so far. You need to take user input into a separate variable and then add it. Something like:

for(i = 0; i < 10; i++)
{
    cout << "enter a number" << endl;
    int input;
    cin >> input;
    number += input;
}

A couple of things. You need to initialize i before you use it in a for loop

for(int i=0; i<10; i++)

Also, you are using the same variable to get the number from cin as you are using to store the sum. You should use two separate variables.

Here's a list of things to change and a working program with a few modifications below 1.You must initialize variables before you can use them in any meaningful way. Initialize means assigning an initial value but it also requires you declare variables and that they are properly defined (eg loop variable is i NOT defined to be an int) Therefore, you have to initialize the for loop variable i. You also have to initialize number by changing it to 0
2. Use a different number for your input and for your sum because you will just overwrite any old values as you read them. Note that you do not need to assign a value to this number because you are reading from the input stream into it

    int sum=0,n;//n is input

    for(int i=0; i < 10; i++)
    {
        cout << "enter a number" << endl;
        cin >> n;
        sum+= n;

    }

    cout << sum;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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