【发布时间】:2023-04-07 11:30:01
【问题描述】:
我正在为学校做一个项目,所以我不想找人为我做我的工作,但我想不通。我需要编写一个程序,将基数为 10 的数字转换为二进制和十六进制。我不知道为什么我的代码没有打印出二进制数。结果总是打印出 0001 并且不获取整个输出。老实说,我不擅长解释这一点,但这是代码。
#include<stdio.h>
#define MAX 1000
int main()
{
long int baseTenNum,remainder,hexQuotient;
int i=1,j,temp;
char hexNum[MAX], binaryNum[MAX];
printf("Enter any Base10 number: ");
scanf("%ld",&baseTenNum);
// quotient variable to convert to hexidecimal value
hexQuotient = baseTenNum;
// while loop to get hexidecimal value
while(hexQuotient!=0)
{
temp = hexQuotient % 16;
// Converts integer to character
if( temp < 10)
temp =temp + 48;
else
temp = temp + 55;
hexNum[i++]= temp;
hexQuotient = hexQuotient / 16;
}
printf("\nhexadecimal value of base 10 number %d: ",baseTenNum);
for(j = i -1 ;j> 0;j--)
printf("%c",hexNum[j]);
printf("\n\n");
if (hexNum[j] = 0){
printf("0000");
}
else if(hexNum[j] = 1){
printf("0001");
}
else if(hexNum[j] = 2 ){
printf("0010");
}
else if(hexNum[j] = 3 )
{
printf("0011");
}
else if(hexNum[j] = 4 ){
printf("0100");
}
else if(hexNum[j] = 5 ){
printf("0101");
}
else if(hexNum[j] = 6){
printf("0110");
}
else if(hexNum[j] = 7 ){
printf("0111");
}
else if(hexNum[j] = 8 ){
printf("1000");
}
else if(hexNum[j] = 9 ){
printf("1001");
}
else if(hexNum[j] = "A" ){
printf("1010");
}
else if(hexNum[j] = "B" ){
printf("1011");
}
else if(hexNum[j] = "C" ){
printf(1100);
}
else if(hexNum[j] = "D" ){
printf("1101");
}
else if(hexNum[j] = "E" ){
printf("1110");
}
else if(hexNum[j] = "F" ){
printf("1111");
}
printf("\n%c",hexNum[2]);
return 0;
}
【问题讨论】:
-
注意:1 和 '1' 和 "1" 都非常不同
-
1 是整数 1,'1' 是一个 char,其 ascii 值不是数字 1,而“1”是一个 指针 到一个常量 char 数组,它不能很好地进行比较