gpt4 book ai didi

c - 在 C 中打印和使用数组元素

转载 作者:行者123 更新时间:2023-11-30 17:35:10 24 4
gpt4 key购买 nike

所以我想做的是输入一个数组,然后使用它的元素。例如:

#include <stdio.h>
#include <string.h>

int main()
{
int s[100],i;

for(i=0; i < strlen(s); ++i)
{scanf("%d",&s[i]);}

printf("s[1] = %d",s[1];

}

如果我输入 12345,我希望它返回 s[1],即 2。我知道如何打印整个数组,但我只想要一个或多个元素,而且似乎我无法计算出这一点看似简单的问题。

最佳答案

for(i=0; i < strlen(s); ++i)

使用未初始化(不确定)的变量可能会产生令人惊讶的结果。无论如何,您需要此处的元素计数:sizeof s/sizeof *s

{scanf("%d",&s[i]);}

始终测试 scanf 中分配了多少个元素。顺便说一句,这是中止的第二个条件。
另外,如果您只想转换一位数字,请使用字段长度:"%1d"

If I input 12345, I want it to return s[1], which would be 2. I know how to print the whole array, but I just want one or more elements, and it seems I can't figure this seemingly easy problem.

看起来您想要读取数字字符串,而不是数字。使用这个:

char digits[100];
if(scanf("%99[0-9]", digits) != 1)
abort();

上面可以读取最多 99 位数字的字符串,如果没有找到数字则中止。

关于c - 在 C 中打印和使用数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23062973/

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