C++ 中的数组赋值错误,我的代码有什么问题?
我正在用CodeBlocks尝试此代码,但结果是一些随机数! 如果您检查代码,请让我知道我的错误是什么。它应该导致乘数为25:
#include <iostream>
using namespace std;
main(){
const int array_size = 10;
int numbers[array_size];
int counter = 0;
while(counter < array_size){
numbers[counter] = 25 * counter;
counter++;
cout << "number[" << counter << "] = " << numbers[counter] << endl;
}
}
事先感谢。
I am trying this code in CodeBlocks but the result is some random numbers!
I appreciate if you check the code and let me know what my mistake is. It should result in multipliers of 25:
#include <iostream>
using namespace std;
main(){
const int array_size = 10;
int numbers[array_size];
int counter = 0;
while(counter < array_size){
numbers[counter] = 25 * counter;
counter++;
cout << "number[" << counter << "] = " << numbers[counter] << endl;
}
}
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在设置
numbers[counter]
的值后,您将递增counter
。在那之后。numbers[counter]
(具有counter
的新值)是一个新的未初始化元素。您应该在打印之后移动增量:
或者干脆避免使用数组(在本例中):
另一种方法是使用两个循环——一个用于初始化,一个用于打印:
You are incrementing
counter
after setting the value ofnumbers[counter]
. After that.numbers[counter]
(with the new value ofcounter
) is a new uninitialized element.You should move the increment after the printing:
Or simply avoid using an array (in this case):
Another way is using two loops -- one for initialization and one for printing:
在增加变量
Counter
后,您将输出数组的非初始化元素。错误的原因是使用不适当的循环。
而不是随行循环,而是用于循环。
例如,
请注意没有参数的函数主体应像
这样声明您可能不会省略函数返回类型。
You are outputting an uninitialized element of the array after incrementing of the variable
counter
.The reason of the error is usage of an inappropriate loop.
Instead of the while loop it is better to use for loop.
For example
Pay attention to that the function main without parameters shall be declared like
That is you may not omit the function return type.
更改此代码
change for this code