程序逐步执行失败

时间:2018-02-03 13:06:03

标签: c

#include<math.h>
#include<stdio.h>
#include<conio.h>
int binaryToDecimal(long binarynum){
    int decimalnum = 0, temp = 0, remainder;
    while(binarynum!=0){
        remainder = binarynum % 10;
        remainder = binarynum / 10;
        decimalnum = decimalnum+remainder*pow(2,temp);
        temp++;
    }
    return decimalnum;
}
long decimalToBinary(int n){
    int remainder;
    long binary = 0,i = 1;
    while(n != 0){
        remainder = n % 2;
        n = n / 2;
        binary = binary + (remainder*i);
        i = i*10;
    }
    return binary;
}
int main(){
    int quotient, rem,decimalnum1,decimalnum2;
    long binarynum1, binarynum2;

    printf("Enter dividend binary number::");
    scanf("%ld",&binarynum1);

    printf("Enter divisor binary number::");
    scanf("%ld",&binarynum2);
    /// execution stops from here.
    decimalnum1 = binaryToDecimal(binarynum1);
    decimalnum2 = binaryToDecimal(binarynum2);
    quotient = decimalnum1/decimalnum2;
    rem = decimalnum1%decimalnum2;
    printf("Quotient  is: %ld",decimalToBinary(quotient));
    printf("Remainder is: %ld",decimalToBinary(rem));
    getch();
}

我正在使用该程序来执行二进制数之间的划分。但 程序执行在第6个语句后停止。我试图改变变量类型但仍有问题。

程序执行的输出在这里。

Output

2 个答案:

答案 0 :(得分:3)

binaryToDecimal函数中存在无限循环问题。

int binaryToDecimal(long binarynum){
    int decimalnum = 0, temp = 0, remainder;
    while(binarynum!=0){
        remainder = binarynum % 10;
        remainder = binarynum / 10;
        decimalnum = decimalnum+remainder*pow(2,temp);
        temp++;
    }
    return decimalnum;
}

改变binarynum变量的部分在哪里?看,它永远不会在循环中发生变化,因此它永远不会为0.你的循环永远运行。

答案 1 :(得分:0)

您的binaryToDecimal函数在无限循环中运行。请尝试以下功能。

int binaryToDecimal(long n)
{
    int decimalNumber = 0, i = 0, remainder;
    while (n!=0)
    {
        remainder = n%10;
        n /= 10;
        decimalNumber += remainder*pow(2,i);
        ++i;
    }
    return decimalNumber;
}