整数除以零

时间:2014-06-19 20:20:45

标签: c++ integer-division

返回的错误是#34; Homework_3_Problem_15.exe中的0x01355144处的未处理异常:0xC0000094:整数除零。"

我可以看到变量' greatCommonDivisor'被赋值为0,但我无法弄清楚原因。

这是我的代码:

#include "stdafx.h"
#include <iostream>
using namespace std;

int greatestCommonDivisor;

void inputNumbers(int& numerator, int& denominator);
int convertToGreatestCommonDivisor(int numerator, int denominator);
void convertToLowestTerms(int& numerator, int& denominator);

int _tmain(int argc, _TCHAR* argv[])
{
    int numerator = 1;
    int denominator = 1;

    inputNumbers(numerator, denominator);
    convertToGreatestCommonDivisor(numerator, denominator);
    convertToLowestTerms(numerator, denominator);

    return 0;
}

void inputNumbers(int& numerator, int& denominator)
{
    cout << "\n";
    cout << "Please enter the numerator: ";
    cin >> numerator;
    cout << "Please enter the denominator: ";
    cin >> denominator;
    cout << "\n";
    return;
}

int convertToGreatestCommonDivisor(int numerator, int denominator)
{
    int greatestCommonDivisor;
    int i;
    // checks if i is greater than the numerator *and* the denominator
    for (i = 1; i <= numerator && i <= denominator; i++)
    {
        if (numerator % i == 0 && denominator % i == 0)
        {
            greatestCommonDivisor = i;
        }
    }
    return (greatestCommonDivisor);
}

void convertToLowestTerms(int& numerator, int& denominator)
{
    cout << "The fraction " << numerator << " / " << denominator << " reduces to " <<
    (numerator / greatestCommonDivisor) << " / " << (denominator / greatestCommonDivisor);
}

非常感谢您提供的任何帮助。

4 个答案:

答案 0 :(得分:3)

您似乎误解了从函数返回的工作方式。

convertToGreatestCommonDivisor中,您有一个名为greatestCommonDivisor的局部变量。您为此分配了一些值,然后return。当您致电convertToGreatestCommonDivisor(numerator, denominator);时,您忽略了此返回值。

然后,convertToLowestTerms使用在第5行声明的全局变量greatestCommonDivisor。此变量的值为0.

您可能希望存储从convertToGreatestCommonDivisor返回的值,然后将其传递给convertToLowestTerms

int greatestCommonDivisor = convertToGreatestCommonDivisor(numerator, denominator);
convertToLowestTerms(greatestCommonDivisor, numerator, denominator);

这需要向convertToLowestTerms添加其他参数。根本不需要全局变量。

答案 1 :(得分:1)

int greatestCommonDivisor;

全局且未初始化时,自动等于0。我想你打算这样做:

greatestComonDivisor = convertToGreatestCommonDivisor(numerator, denominator);

答案 2 :(得分:1)

由于greatestCommonDivisor是全球性的,您只需将convertToGreatestCommonDivisor功能更改为

即可
void convertToGreatestCommonDivisor(int numerator, int denominator)  //Change return type to void
{
    // Remove the local variable "greatestCommonDivisor"
    int i;
    // checks if i is greater than the numerator *and* the denominator
    for (i = 1; i <= numerator && i <= denominator; i++)
    {
        if (numerator % i == 0 && denominator % i == 0)
        {
            greatestCommonDivisor = i;
        }
    }
    //Remove the return statement
}

答案 3 :(得分:0)

您有2个greatestCommonDivisor个变量,一个是全局变量,一个是本地变量。全局值1始终为0,未定义或保留一些随机值,具体取决于您的环境构建类型等。