如果num
的類型爲int
,那麼此程序將工作。但是當將其更改爲int8_t
時,num
將在scanf()
後始終爲0。int8_t類型的變量總是從scanf獲得值0
這是因爲%d
在scanf
?
#include <stdio.h>
#include <stdint.h>
void convert(int8_t, int8_t);
int main(int argc, char const *argv[]) {
int8_t num;
int8_t b;
printf("enter a number:\n");
while (1 == scanf("%d", &num)) {
scanf("%d", &b);
printf("%d %d\n", num, b);
printf("Code: ");
convert(num, b);
putchar('\n');
printf("enter a integer (q to quit):\n");
}
printf("done.\n");
getchar();
return 0;
}
void convert(int8_t n, int8_t base) {
if (n >= base)
convert(n/base, base);
printf("%d", n % base);
return;
}
1)閱讀'scanf'手冊,2)啓用編譯器警告,3)不對編譯器說謊。 –
http://en.cppreference.com/w/c/types/integer檢查格式部分 –