【发布时间】:2014-02-27 11:42:33
【问题描述】:
我似乎无法让我的输出正常工作。我想这样做,以便括号中的最后一个余数在第一行间距之后的一列中完美排列。除了最后一部分之外,我拥有大部分输出权利,它必须完全符合我的教授想要的方式。
我能想到的最好的是EDITED:
Marcus Lorenzana
314156 = 19634 * 16 + 12 (C)
19634 = 1227 * 16 + 2 (2)
1227 = 76 * 16 + 11 (B)
76 = 4 * 16 + 12 (C)
4 = 0 * 16 + 4 (4)
0x4CB2C
这是我想要的输出:
Marcus Lorenzana
314156 = 19634 * 16 + 12 (C)
19634 = 1227 * 16 + 2 (2)
1227 = 76 * 16 + 11 (B)
76 = 4 * 16 + 12 (C)
4 = 0 * 16 + 4 (4)
0x4CB2C
但正如您所见,输出并不完全正确。
这是我的程序已编辑:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER 50
static int base = 16;
int main(int argc, char * argv[]) {
printf("Marcus Lorenzana\n");
if (argc == 2) {
char hexstr[] = "0123456789ABCDEF";
int i = 0;
long long oldresult;
int remainder;
char remainders[BUFFER];
char w_num[BUFFER];
long long value = atoll(argv[1]);
//Get width of original number for formatting purposes
int vwidth = strlen(argv[1]);
char oldwidth[BUFFER];
//Convert the decimal to hexadecimal
while(value != 0) {
oldresult=value;
remainder = value%base;
value = value/base;
//Store the remainder in an array for later use
remainders[i]=hexstr[remainder];
char line[BUFFER];
//Get length of line for formatting purposes
int w = sprintf(line,"%*lld = %-*lld * %2d + %2d", \
vwidth,oldresult,vwidth,value,base,remainder);
printf("%s (%c)\n", line,hexstr[remainder]);
i++;
}
//Print the the hexadecimal number
int x = i;
printf("0x");
while(x > 0) {
printf("%c",remainders[--x]);
}
printf("\n");
} else {
printf("Error: Wrong arguments\n");
return 1;
}
return 0;
}
【问题讨论】:
-
而不是
50,使用firstw计算(并加1)。 -
如何为接下来的几行计算第一个 w?导致 w 根据新值发生变化。
-
那么你可以在
w_max中使用w的最大值,因为这发生在第一行......瞧 -
我明白了,谢谢 :)
标签: c formatting hex printf output