gpt4 book ai didi

c - 数组的奇数输出

转载 作者:行者123 更新时间:2023-12-02 05:23:57 25 4
gpt4 key购买 nike

我正在阅读 Stephen G. Kochan 的“C 语言编程”一书学习数组。尽管我花了很长时间试图找出语法错误,但我已经到了对输出感到非常困惑的地步。

这是我的代码:

#include <stdio.h>

int main (void)
{
int values[10];
int index;

values[0] = 197;
values[2] = -100;
values[5] = 350;
values[3] = values[0] + values[5];
values[9] =
values[5] / 10;
--values[2];

for ( index = 0; index < 10; ++index )
printf("values[%i] = %i\n", index, values[index]);

return 0;
}

根据书本应该如何输出:

values[0] = 197
values[1] = 0
values[2] = -101
values[3] = 547
values[4] = 0
values[5] = 350
values[6] = 0
values[7] = 0
values[8] = 0
values[9] = 35

我的输出是这样的:

values[0] = 197
values[1] = -2
values[2] = -101
values[3] = 547
values[4] = 4200832
values[5] = 350
values[6] = 4200926
values[7] = 4200832
values[8] = 7680288
values[9] = 35

就好像所有的零(未初始化的值)都被这些大数字代替了。这是怎么回事,我该如何改变它?

更新

Peter Griffiths 提到了这一点,这是来自 Stephen G. Kochan 的“Programming in C 3rd edition”一书的引述:

Because you never assigned values to five of the elements in the array - elements 1, 4, and 6 through 8 - the values that are displayed for them are meaningless. Even though the program's output shows these values as zero, the value of any uninitialized variable or array element is not defined. For this reason, no assumption should ever be made as to the value of an uninitialized variable or array element.

这清楚地表明这本书没有任何问题。所以这不是一本坏书!目前只有良好的体验!

我使用的是 Windows 7 家庭高级版 64 位,并且我使用的是 gcc (GCC) 4.7.2 编译器。不同输出的原因可能是不同的操作系统和编译器。

最佳答案

这是那本书的引述,来自您引述输出后立即的段落:

Because you never assigned values to five of the elements in the array - elements 1, 4, and 6 through 8 - the values that are displayed for them are meaningless. Even though the program's output shows these values as zero, the value of any uninitialized variable or array element is not defined. For this reason, no assumption should ever be made as to the value of an uninitialized variable or array element.

寓意:当你真正阅读编程书籍时,你会从中收获更多。

关于c - 数组的奇数输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17709392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com