加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么我需要将int变量初始化为0?

发布时间:2020-12-16 10:44:00 所属栏目:百科 来源:网络整理
导读:我刚刚制作了这个程序,要求输入5到10之间的数字,然后计算这里输入的数字的总和就是代码 #include iostream#include cstdlibusing 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 "Wr
我刚刚制作了这个程序,要求输入5到10之间的数字,然后计算这里输入的数字的总和就是代码

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

如果我输入数字5,它应该显示

The sum of the first 5 numbers are 15

但它显示出来

The sum of the first 5 numbers are 2293687

但是当我把c设为0时

它的核心工作

那么区别是什么呢 ?

解决方法

因为C不会自动为您设置零.所以,你应该自己初始化它:

int c = 0;

未初始化的变量具有随机数,例如2293687,-21,99999,……(如果在读取时未调用未定义的行为)

此外,静态变量将设置为其默认值.在这种情况下0.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读