gpt4 book ai didi

C 程序显示一个正方形而不是字符串

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

我已经用 Java 做了很多工作,但我目前正在尝试学习 c。我正在尝试编写一个程序将数字从十进制转换为二进制。

这是我的:

#include <stdio.h>
#define LENGTH 33

int main( int argc, char*argv[ ] )

{
unsigned int number, base, remainder, x, i;
char result[LENGTH];

puts( "Enter a decimal value, and a desired base: " );
scanf( " %u", &number );
scanf( " %u", &base );

x = number;

for( i=0; i < LENGTH; i++ )
{
remainder = x % base;
x = x/base;
result[i] = remainder;
}

printf( "%u equals %s (base-%u) \n", number, result, base );

//***result is probably backwards...


return 0;



}

这是我运行它时得到的结果:

Enter a decimal value, and a desired base: 
5 2
5 equals (base-2)

什么是正方形以及如何将其显示为字符串(字符数组)?

最佳答案

上次编辑:您的程序可能如下所示:

 unsigned int number, base, remainder, x, i;
char result[LENGTH+1] = {0};

puts( "Enter a decimal value, and a desired base: " );
scanf( " %u", &number );
scanf( " %u", &base );

x = number;

for( i=0; i < LENGTH; i++ )

{
// if base > 10, use alphabet!
result[i] = remainder > 9 ? (remainder-10) + 'A' : remainder + '0';
x = x/base;
result[i] = remainder + '0';
}

首先,在写余数的时候,要加上数字的ASCII偏移量。

  result[i] = remainder + '0';

还有,你忘了在最后添加'\0'

 result[i] = 0;
printf( "%u equals %s (base-%u) \n", number, result, base );

编辑:写入 C 字符串时,我通常将字符串初始化为零:

char result[LENGTH] = {0};

这样你就不需要在末尾写null character了,它是为你写的。


感谢@mmyers 指出溢出 :)我会声明要保存 LENGTH+1 的字符串:

char result[LENGTH+1] = {0};

关于C 程序显示一个正方形而不是字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1467212/

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