我在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) 什么是正方形,以及如何将其显示为字符串(char数组)?
发布于 2009-09-23 16:42:35
上次编辑:您的程序可能如下所示:
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-时,我通常将字符串初始化为0:
char result[LENGTH] = {0};这样你就不需要在最后写null character了,它是为你写的。
感谢@mmyers指出溢出:)我将声明包含LENGTH+1的字符串
char result[LENGTH+1] = {0};发布于 2009-09-23 16:47:31
您希望将数字存储为result[i]中的字符,而不是作为余数的实际数字。要做到这一点,一种方法是索引到一个辅助数组(可以是字符串字面量),该数组具有您想要的数字。
char digits[] = "0123456789ABCDEF";
/* stuff */
result[i] = digits[remainder];
/* more stuff */另外,告诉您使用null终止字符串的其他注释是完全正确的。
编辑:无论您走哪条路由,都应该确保base的输入值大于0,并且不大于您希望处理的最大值。
发布于 2009-09-23 16:43:56
您需要确保您的字符串具有介于32和127之间的值才能在终端上显示。
for( i=0; i < LENGTH; i++ )
{
remainder = x % base;
x = x/base;
result[i] = remainder;
}在本节中,您将把较小的值放入数组中,因此它不会显示为ASCII字母。
你可能只想要像这样的东西: resulti =余数+ '0';
一种简单的查看方法是打印出字符串的每个部分的ascii值,并查看值是什么。
https://stackoverflow.com/questions/1467212
复制相似问题