我创建了一个程序,可以手动将以 10 为基数的数字转换为任何其他基数。我认为重要的事情在起作用,但有几个问题我无法解决。
我遇到的一个问题是每行最右边括号中的余数的格式没有正确排列。我意识到这并不是真正必要的事情,但我的教授希望输出是这样的,如果不是这样,我会扣分。 已修复
我遇到的一个更大的问题是输出的最后一行,即十六进制数,将是正确的,但有时会有一个杂散的 ASCII 字符或 0x 和十六进制之间的几个空格。
这是错误输出的示例 UPDATE:
Marcus Lorenzana
8526495043095935640 = 532905940193495977 * 16 + 8 (8)
532905940193495977 = 33306621262093498 * 16 + 9 (9)
33306621262093498 = 2081663828880843 * 16 + 10 (A)
2081663828880843 = 130103989305052 * 16 + 11 (B)
130103989305052 = 8131499331565 * 16 + 12 (C)
8131499331565 = 508218708222 * 16 + 13 (D)
508218708222 = 31763669263 * 16 + 14 (E)
31763669263 = 1985229328 * 16 + 15 (F)
1985229328 = 124076833 * 16 + 0 (0)
124076833 = 7754802 * 16 + 1 (1)
7754802 = 484675 * 16 + 2 (2)
484675 = 30292 * 16 + 3 (3)
30292 = 1893 * 16 + 4 (4)
1893 = 118 * 16 + 5 (5)
118 = 7 * 16 + 6 (6)
7 = 0 * 16 + 7 (7)
����76543210FEDCBA98
它应该看起来像这样:
Marcus Lorenzana
2147483647 = 134217727 * 16 + 15 (F)
134217727 = 8388607 * 16 + 15 (F)
8388607 = 524287 * 16 + 15 (F)
524287 = 32767 * 16 + 15 (F)
32767 = 2047 * 16 + 15 (F)
2047 = 127 * 16 + 15 (F)
127 = 7 * 16 + 15 (F)
7 = 0 * 16 + 7 (7)
0x7FFFFFFF
这是我的程序已更新:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER 50
static const char hexstr[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int main(int argc, char * argv[]) {
if (argc == 3) {
int base = atoi(argv[1]);
int i = 0;
long oldresult;
int remainder;
char remainders[BUFFER];
char w_num[BUFFER];
long value = atol(argv[2]);
int width = sprintf(w_num,"%ld",value);
printf("Marcus Lorenzana\n");
while(value != 0) {
oldresult=value;
remainder = value%base;
value = value/base;
remainders[i]=hexstr[remainder];
char line[BUFFER];
int w = sprintf(line,"%*ld = %ld * %d + %d", \
width,oldresult,value,base,remainder);
printf("%s%*s(%c)\n",line,50-w,"",hexstr[remainder]);
i++;
}
int x = strlen(remainders);
while(x > 0) {
printf("%c",remainders[--x]);
}
printf("\n");
} else {
printf("Error: Wrong arguments\n");
}
return 0;
}
最佳答案
使用 printf()
的返回值来确定在余数之前打印多少个空格。
int w = printf("%*lld = %lld * %d + %d",width,oldresult,value,base,remainder);
if (remainder > 9) {
remainders[i]=hexstr[remainder-10];
// Here and in the else clause
printf("%*s(%c)\n", 34-w, "", hexstr[remainder-10]);
}
第二期:更改x
的测试和递减方式。看不到 "0x"
出现的位置。
while(x > 0) {
printf("%c",remainders[--x]);
}
注意:似乎 static const char hexstr[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
会简化事情。
[编辑]
对第二个问题的简单修复,因为 remainders
永远不会正确地 \0
终止。
// int x = strlen(remainders);
int x = i;
关于c - 如何为该程序正确格式化输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21471632/