#include <iostream>
#include<conio.h>
using namespace std;
int main()
{
int Array[5];
int i;
int total;
int j;
for(i=0; i<5; i++)
{
cout<<"Enter the Numbers : ";
cin>>Array[i];
}
total+=Array[i];
cout<<total<<endl;
getch();
return 0;
}
我试过上面的代码。 我想要做的是添加从用户获取的数字,但我得到一些其他结果.. 谁能告诉我如何在上面的程序中添加输入? 提前谢谢
答案 0 :(得分:3)
这是因为你没有初始化total
。声明局部变量时,它的值是未定义的,并且向未定义的值添加内容会导致未定义的行为。
实际上,未初始化的局部变量的值是变量现在占用的内存位置中的任何值,并且看似随机。
您还遇到的问题是,您实际上并未添加数组中的所有条目,只有索引j
中的条目,这也是未初始化的变量,导致您从随机位置获取值(并且最有可能超出阵列的极限。)
你实际上不需要数组,只有三个变量:循环计数器i
,total
(你应该初始化为零)和一般{输入语句中使用的{1}}整数。
然后你做了。
value
注意:您不需要在我的示例中初始化int total = 0;
for (int i = 0; i < 5; ++i)
{
std::cout << "Enter a number: ";
int value;
std::cin >> value;
total += value;
}
std::cout << "Total is " << total << '\n';
变量,因为它不会被读取,只会在输入语句中写入(并因此被初始化)。
答案 1 :(得分:2)
由于已经解释了您的问题,以下是您的计划如何缩短形式:
#include <iterator>
#include <algorithm>
#include <iostream>
int main()
{
std::cout << "The total is ";
std::cout << std::accumulate(std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(), 0);
std::cin.get();
}
答案 2 :(得分:0)
您的变量j
未初始化。
您可能希望使用cin.ignore(10000,'\n')
代替getch()
。
此外,conio
不是标准,在您的计划中不是必需的。
答案 3 :(得分:0)
total
和j
都未初始化,因为它们是局部变量,所以initial value未确定。所以这一行的结果也未确定:
total+=Array[j];
修改
所以你编辑了你的问题,现在该行:
total+=Array[i];
但由于total
仍未初始化,结果仍未定义。此外,您似乎可能打算在for
循环中包含该行,目前它在外面。这意味着i
将是5
,您也将访问越界。通过一些小的编辑,这应该做你想要的:
int total = 0 ;
for(i=0; i<5; i++)
{
cout<<"Enter the Numbers : ";
cin>>Array[i];
total+=Array[i];
}
答案 4 :(得分:0)
int total = 0;
// Add second loop for total (or better, add it in the first one)
for(i=0; i<5; i++)
{
total += array[i];
}
答案 5 :(得分:0)
试试这个:
#include <iostream>
using namespace std;
int main()
{
int Array[5], i, total=0;
for(i=0; i<5; i++)
{
cout<<"Enter the Numbers : ";
cin>>Array[i];
total = total + Array[i];
}
cout<<"The sum is: "<<total<<endl;
return 0;
}
答案 6 :(得分:0)
请参阅以下代码和解释说明
#include <iostream>
//#include<conio.h> we dont need this and it is obsolete
using namespace std;
int main()
{
int Array[5];
int i;
int total;
int j;
for(i=0; i<5; i++)
{
cout<<"Enter the Number : ";
cin>>Array[i];
total+=Array[i]; //this should come inside the loop so that each element gets added to the total
}
cout<<total<<endl;
cin.ignore(); //use this over getchar() and cin.get() as it doesn't leave the input on the stream
return 0;
}