Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I just made this program which asks to enter number between 5 and 10 and then it counts the sum of the numbers which are entered here is the code

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    int a,i,c;
    cout << "Enter the number between 5 and 10" << endl;
    cin >> a;
    if (a < 5 || a > 10)
    {
        cout << "Wrong number" << endl;
        system("PAUSE");
        return 0;
    }
    for(i=1; i<=a; i++)
    {
        c=c+i;
    }
    cout << "The sum of the first " << a << " numbers are " << c << endl;
    system("PAUSE");
    return 0;
}

if i enter number 5 it should display

The sum of the first 5 numbers are 15

but it displays

The sum of the first 5 numbers are 2293687

but when i set c to 0

it works corectly

So what is the difference ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
461 views
Welcome To Ask or Share your Answers For Others

1 Answer

Because C++ doesn't automatically set it zero for you. So, you should initialize it yourself:

int c = 0;

An uninitialized variable has a random number such as 2293687, -21, 99999, ... (If it doesn't invoke undefined behavior when reading it)

Also, static variables will be set to their default value. In this case 0.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...