1

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

    #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;

    }
4

2 回答 2

1

看起来好像num1从未初始化过。它将为零,这将导致除以零。

于 2012-10-24T23:21:12.010 回答
0

你的simplify功能有缺陷。这是您打电话时的含义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现在有四个参数。前两个是你要在计算中使用的值(我们不需要指针),指针只用于将结果分配给传入的地址。

于 2012-10-24T23:34:55.477 回答