我需要获得两个输入--十六进制地址和位数--然后我需要打印出地址的索引和偏移量。
因此,如果输入为20和0x0FF10100,则索引的输出应为0x0FF1,偏移的输出应为0100。
int bits, index, offset, count;
short addr[10], addr2;
printf("# of bits: ");
scanf("%d", &bits);
index = (bits / 4) + 2;
offset = 10 - index;
printf("Integer (in hex): ");
scanf("%hi", addr);然后我需要输出索引,它是(20/4)+2 =7,这意味着地址的前7个字符。其余部分作为偏移量。
我不能使用printf,我试过很多次了。但是我修不好,希望有人能帮上忙
谢谢大家。
对于输出,我尝试使用
while (count < index)
{
printf("", addr[count], addr[count]);
count++;
}它没有打印出任何东西...
然后,我尝试了许多变体,但我得到了错误。我不知道用什么来输出..
谢谢
发布于 2011-01-28 07:11:20
也许我漏掉了什么,但是printf调用使用的是空字符串,而不是格式化字符串。您可以看到各种格式说明符here。
发布于 2011-01-28 08:48:29
如果您打算使用输入,请始终检查scanf的返回值;它将返回已成功扫描的项目数。如果忽略返回值,您可能会尝试读取不确定的值,这意味着您的程序具有未定义的行为。
此外,在第二次调用scanf时,您要求的不是十六进制整数,而是短整型(h表示短整数,i表示整数)。如果要扫描十六进制短整型,则需要使用hx,但这也意味着需要提供unsigned short的地址,而不是普通的short。
int bits, index, offset, count;
unsigned short addr[10], addr2;
printf("# of bits: ");
if (scanf("%d", &bits) != 1)
{
// could not scan
// handle scan error here. Exit, or try again, etc.
}
index = (bits / 4) + 2;
offset = 10 - index;
printf("Integer (in hex): ");
if (scanf("%hx", addr) != 1)
{
// could not scan
// do whatever makes sense on scan failure.
}如果您正在读取addr数组的连续元素,则可能需要以下内容:
printf("Integer (in hex): ");
if (scanf("%hx", &addr[count]) != 1)
{
// could not scan
// do whatever makes sense on scan failure.
}最后,关于printf的使用:printf的第一个参数告诉它如何打印提供的数据。您为它提供了一个空字符串,这意味着printf不会被告知打印任何内容。也许你正在寻找类似这样的东西:
printf("%d: %hx", count, addr[count]);https://stackoverflow.com/questions/4822867
复制相似问题