【发布时间】:2018-08-26 16:07:53
【问题描述】:
我的程序为 Decimal 提供了正确的值,但我使用 char 来为 Hex 设置 gt 值
谁能看到我的代码并告诉我为什么我的输出只是一个“?” (附上我的输出作为图像)
我知道你可以添加 char 值。
这是我的代码。请不要试图更改我的整个代码,说我正在做的是“更长的路”。
请注意,我现在只测试 HexVal1,因为它只考虑前 4 位。
程序应该做的是取二进制的前 4 位并抛出一个十六进制字符。
#include <math.h>
#include <stdio.h>
int main()
{
int bit1,bit2,bit3,bit4,bit5,bit6,bit7,bit8;
int dec1,dec2,dec3,dec4,dec5,dec6,dec7,dec8;
char hex1,hex2,hex3,hex4,hex5,hex6,hex7,hex8;
int BinVal;
char HexVal1;
char HexVal2;
printf("Please enter the first bit(0 or 1): ");
scanf("%d",&bit1);
printf("Please enter the second bi(0 or 1): ");
scanf("%d",&bit2);
printf("Please enter the third bit(0 or 1): ");
scanf("%d",&bit3);
printf("Please enter the fourth bit(0 or 1): ");
scanf("%d",&bit4);
printf("Please enter the fifth bit(0 or 1): ");
scanf("%d",&bit5);
printf("Please enter the sixth bit(0 or 1): ");
scanf("%d",&bit6);
printf("Please enter the seventh bit(0 or 1): ");
scanf("%d",&bit7);
printf("Please enter the eigth bit:(0 or 1): ");
scanf("%d",&bit8);
if(bit1==1){
dec1=1;
hex1='1';
}
else{
dec1=0;
hex1='0';
}
if(bit2==1){
dec2=2;
hex2='2';
}
else{
dec2=0;
hex2='0';
}
if(bit3==1){
dec3=4;
hex3='4';
}
else{
dec3=0;
hex3='0';
}
if(bit4==1){
dec4=8;
hex4='8';
}
else{
dec4=0;
hex4='0';
}
if(bit5==1){
dec5=16;
hex5='16';
}
else{
dec5=0;
hex5='0';
}
if(bit6==1){
dec6=32;
hex6='32';
}
else{
dec6=0;
hex6='0';
}
if(bit7==1){
dec7=64;
hex7='64';
}
else{
dec7=0;
hex7='0';
}
if(bit8==1){
dec8=128;
hex8='128';
}
else{
dec8=0;
hex8='0';
}
BinVal=dec1+dec2+dec3+dec4+dec5+dec6+dec7+dec8;
printf("Binary value for your decimal number is %d",BinVal);
HexVal1=sizeof(hex1)+sizeof(hex2)+sizeof(hex3)+sizeof(hex4);
if(HexVal1==15){
HexVal1='F';
}
else if (HexVal1==14){
HexVal1='E';
}
else if (HexVal1==13){
HexVal1='D';
}
else if(HexVal1==12){
HexVal1='C';
}
else if(HexVal1==11){
HexVal1='B';
}
else if(HexVal1==10){
HexVal1='A';
}
printf("\nHex Val for first 4 bits is %c", HexVal1);
return 0;
}
输出如下
Please enter the first bit(0 or 1): 1
Please enter the second bi(0 or 1): 0
Please enter the third bit(0 or 1): 0
Please enter the fourth bit(0 or 1): 1
Please enter the fifth bit(0 or 1): 1
Please enter the sixth bit(0 or 1): 1
Please enter the seventh bit(0 or 1): 1
Please enter the eigth bit:(0 or 1): 1
Binary value for your decimal number is 249
Hex Val for first 4 bits is
【问题讨论】:
-
你为什么要这样做:
HexVal1=sizeof(hex1)+sizeof(hex2)+sizeof(hex3)+sizeof(hex4); -
你知道
sizeof是做什么的吗?hex8='128'不合法,hex8只能容纳单个字符,'128'是多字符字符常量 -
检查我发布的图片的超链接,你会看到程序应该做什么
-
@MuhammadShaeelAbbas 请不要张贴输出图片,将输出复制并粘贴到您的问题中!
-
如果你有一个整数并且你想以十进制和十六进制打印出来,只需使用
printf与%d和%x。如果您想学习如何操作单个位和字节,并自己进行“十六进制转换”,请使用循环、移位和掩码,或乘法和除法。有关提示,请参阅 C FAQ list(和 this footnote)中的 question 20.10。