在.c

2017-11-18 39 views
-1

一个简单的印刷错误我只是写一个程序来更改十进制数到另一个基地(2 < =基数< = 16)。
运行该程序并打印正确的答案后,我遇到一个错误消息:“程序已停止工作”。你可以看看我的代码,并找到它挂在哪里??? !!!我真的很困惑。
这是我的代码:在.c

int decimal, radix, pow = 1, temp; 
printf("enter your number and the 2 <= radix <= 16\n"); 
scanf("%d%d",&decimal, &radix); 
temp = decimal; 
for(; temp >= radix; temp /= radix)// finding the greatest exponent of radix in decimal 
    pow *= radix; 
while(pow >= 1){ 
    decimal -= temp * pow; 
    if(temp == 10) 
     printf("A"); 
    else if(temp == 11) 
     printf("B"); 
    else if(temp == 12) 
     printf("C"); 
    else if(temp == 13) 
     printf("D"); 
    else if(temp == 14) 
     printf("E"); 
    else if(temp == 15) 
     printf("F"); 
    else 
     printf("%d",temp); 
    pow /= radix; 
    temp = decimal/pow; 
} 
puts(""); 

我认为这个问题是因为“TEMP =十进制/ POW”,但我怎么能解决这个问题的?

+0

年底计算temp = decimal/pow;有简单的十进制转换到另一个基站的方式。在'pow = 0'时检查是否将'decimal'分开。 – coderredoc

+2

问题是在循环的最后一行用**除**。 –

+0

I.e. 'pow/= radix'的最后一个分区导致'pow'被置为* 0 *,'temp = decimal/pow'具有未定义的行为。 –

回答

2

检查pow为0,当你在while循环

pow /= radix; 
    if (pow > 0) 
    { 
     temp = decimal/pow; 
    } 
+0

哦,我明白了。非常感谢你 。是零划分还抚摸着我的脑海,但我无法找到它等于零的地方。毕竟,调试自己的程序非常困难。 – alirezafnatica