C中分数简化程序的浮点异常

时间:2012-10-24 23:17:39

标签: c floating-point

当我运行以下代码时,我总是得到一个浮点异常。我该如何解决?

    #include <stdio.h>

    //Global Variables

    int num, denom, num1, denom1;

    void simplify(int *numerator, int *denominator);

    int main () {

    //Prompt User as to what program is
    printf("Fraction Simplifier\n");
    printf("===================\n");

    //Ask User for Numerator and Denominator
    printf("Numerator: ");
    scanf("%d", &num);
    printf("Denominator: ");
    scanf("%d", &denom);

    //Call Function
    simplify(&num1, &denom1);

    //Display final output
    printf("%d / %d = %d / %d", num, denom, num1, denom1);

    return 0;
    }

    //Simplify function
    void simplify(int *numerator, int *denominator)
    {

    num = num1;
    denom = denom1;

    num1 = num1 / num1;
    denom1 = denom1 / num1;
    num1 = *numerator;
    denom1 = *denominator;

    }

2 个答案:

答案 0 :(得分:1)

看起来num1永远不会被初始化。它将为零,这将导致除以零。

答案 1 :(得分:0)

您的simplify功能存在缺陷。以下是您致电simplify时的含义:

  

调用简化,传递num1和denom1的地址

以下是简化中的代码意味着:

num = num1;          /* Assign the value of num1 to num, meaning set num to 0. */
denom = denom1;      /* Assign the value of denom1 to denom, meaning set denom to 0. */
num1 = num1 / num1;  /* Divide num1 (which is 0) by num1 (which is 0). Error! */

您可以通过消除全局变量来简化程序并使其更易于理解。这也可以帮助您纠正错误。这是一个重写:

#include <stdio.h>

void simplify(int numerator, int denominator, int* newNumerator, int* newDenominator);

int main () {

    int num, denom, num1, denom1;

    /* Do your input code */

    //Call Function
    simplify(num, denom, &num1, &denom1);

    //Display final output
    printf("%d / %d = %d / %d", num, denom, num1, denom1);

    return 0;
}

//Simplify function
void simplify(int numerator, int denominator, int* newNumerator, int* newDenominator)
{
    int simplifiedNumerator;
    int simplifiedDenominator;

    /* Calculate your results.. left out your original code, which calculates incorrectly */
    /* You will refer to the ints numerator and denominator */

    /* Assign your results */
    *newNumerator = simplifiedNumerator;
    *newDenominator = simplifiedDenominator;
}

请注意,simplify现在有四个参数。前两个是您要在计算中使用的值(我们不需要指针),指针仅用于将结果分配给传入的地址。