gpt4 book ai didi

c - 从c中的字符数组打印整数

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

int main(){
int n,i=0,c1,c2;
char a[1000];
scanf("%d",&n);

while(n!=0)
{
a[i]=n%2;
printf("%d",a[i]); // This prints Values Correctly
n=n/2;
i++;

}
a[i]='\0';
for(i=0;a[i]!='\0';i++)
printf("%d",a[i]); //This prints only the first element of the array
}

我在这里错过了什么?为什么我不能遍历并打印 char 数组的值,尽管当我尝试在 while 循环中打印它时它可以工作?

最佳答案

char 类型的数组用于存储整数,该数组不是字符串。因为您存储除以 2 的余数,所以大多数元素的值为 0。

删除以 null 终止数组的行。变量 i 已经计算了输入的元素数量,因此迭代并打印直到打印 i 个元素。

关于c - 从c中的字符数组打印整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40071354/

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