为什么当我初始化一个变量时,我的代码会给出不同的答案,而当我添加一个像0这样的简单值时呢



下面有两个不同的代码。两者之间的区别只是对于变量sum,sum被初始化,相比之下,sum的值为0sum=0

#include <iostream>
using namespace std;
int main(){

//This code will display first ten numbers and get the sum of it
cout << "The natural numbers are: " << endl;
for(int i=1; i<=10; i++)
{
cout << i << " ";

}
cout << endl;
// variable was initialized 
int sum;
cout << "The sum of first 10 natural numbers: ";
for(int i=1; i<=10; i++)
{
sum = sum +i;
}
cout << sum;
cout << endl;

}

该代码输出:

自然数为:1 2 3 4 5 6 7 8 9 10

前10个自然数之和:32821

程序结束,退出代码为:0

#include <iostream>
using namespace std;
int main(){
//This code will display first ten numbers and get the sum of it
cout << "The natural numbers are: " << endl;
for(int i=1; i<=10; i++)
{
cout << i << " ";

}
cout << endl;
// here I gave the value 1... this time it worked
int sum =0;
cout << "The sum of first 10 natural numbers: ";
for(int i=1; i<=10; i++)
{
sum = sum +i;
}
cout << sum;
cout << endl;

}

该代码输出:

自然数为:1 2 3 4 5 6 7 8 9 10

前10个自然数之和:55

程序结束,退出代码为:0

为什么代码会这样做?有人能向我解释一下他们为什么给我两个不同的金额吗?

如果你不初始化sum,它有一个不确定的值,你无法判断对它的操作。读取未初始化的变量是未定义的行为,这样做会使整个程序无效。

Btw;您似乎对初始化是什么感到困惑。int sum;不会初始化sum,它只是声明了它——它不会给它一个初始值,在给它分配一个已知值之前,你可能不会读取它或在计算中使用它。int sum = 0;初始化sum,也就是说,它给它一个初始值,现在您可以有效地读取它并在计算中使用它。

实际上,在第一组代码中,编译器采用了变量sum的随机值。在您的情况下,我认为编译器将sum的值作为32766。该值CCD_ 9是"0";垃圾值";。

所以,在第二种情况下,你们给sum一个初始值,所以编译器知道用户已经给了一个值。因此,它将相应地执行您给定的操作。在循环内,sum将从0开始并继续执行给定的操作,直到它退出循环。这种情况2代码的操作如下所示:

sum = sum + i; //(here value of "i" increase by 1 with iteration of the given loop)
/* 1 = 0 + 1
3 = 1 + 2
6 = 3 + 3
10 = 6 + 4
15 = 10 + 5
21 = 15 + 6
28 = 21 + 7
36 = 28 + 8
45 = 36 + 9
55 = 45 + 10
As you can see the value of "sum" after the loop is 55
*/

但在第一种情况下,您没有给出sum的初始值,所以编译器不知道sum的值是0、6、15、7还是10。所以,编译器为它取了一个随机值,在您的情况下它是32766。在循环中,它从32766开始并继续其给定的操作。案例1代码的操作如下:-

sum = sum + i; //(like previous case here too value of "i" increase by 1 with iteration of the given loop)
/* 32767 = 32766 + 1
32769 = 32767 + 2
32772 = 32769 + 3
32776 = 32772 + 4
32781 = 32776 + 5
32787 = 32781 + 6
32794 = 32787 + 7
32802 = 32794 + 8
32811 = 32802 + 9
32821 = 32811 + 10
Here you can see the value of "sum" after the operation is 32821
*/

好吧!总的来说,您的逻辑和代码对我来说很好,但在第一种情况下,sum的值是由编译器随机分配的,所以在这里,第一种情况的一切都出错了。

激活编译器标志-Wuninitialized

在第一个程序中,sum保持未初始化状态,并包含垃圾值。因此,您会得到错误。OTOH,在第二个程序中,sum的值被初始化为0,这恰好是零,因此计数成功。

当您编写int sum时;在c++中,内存中为这个变量保留了一个空间,因为它不仅是一个声明,也是一个定义。由于sum还没有设置为任何值,那么,在这种情况下,它会得到存储在它的内存空间中的任何疯狂的值,这些值以前已经存储在那里了。希望它有所帮助:(以下是一些有用的链接:链接1;链接2

相关内容

最新更新