gpt4 book ai didi

c - 为什么 "1"存储在所有数组索引位置?

转载 作者:太空宇宙 更新时间:2023-11-04 05:53:23 25 4
gpt4 key购买 nike

我正在学习和练习 C。除了输出格式。我不明白为什么所有数组元素都输出“1”,或者数字从何而来。

即使我输入 5 个“5”,输出仍然始终是“1”。

#define LIMIT 5
#include <stdio.h>
#include<stdlib.h>
void getNums();

int main() {
getNums();
return 0;
}

void getNums() {
int newRay[LIMIT];
for(int i = 0; i < 5; i++) {
int element;
int result = scanf("%d", &element);
newRay[i] = result;
printf("%d", newRay[i]);
}
}

最佳答案

result 存储scanf 的返回值,即提供给scanf< 的格式字符串中的匹配数/。您真正想要的是读取的值,存储在元素中:

        newRay[i] = element;

注意事项:

  • 最好始终如一地使用 LIMIT。您的程序可能只是“又快又脏”,但无论如何您都应该替换 for 循环中的 5

关于c - 为什么 "1"存储在所有数组索引位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33598350/

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