我在下面创建的基本程序计算2个整数的最大公约数。除零和零的特定组合外,它适用于所有数字。我很确定函数“ greatComDiv()”中的if语句出了点问题,但我无法弄清楚它到底出了什么问题。
#include<iostream>
#include<cmath>
using namespace std;
int greatComDiv(int num1, int num2)
{
//The 2 lines below convert the numbers to their absolute value in case they are negative
num1 = abs(num1);
num2 = abs(num2);
//The if statement below takes care of the case that both numbers are zero the subsequent else statement performs the normal calculations if they are both not zero.
if( num1== 0 && num2 == 0)
{
cout<<"undefined"<<endl;
}
else
{
while(num2 > 0 )
{
num1%num2;
int tempNum = num1%num2;
num1 = num2;
num2 = tempNum;
}
return num1;
}
}
int main()
{
int numb1, numb2;
cout<<"Enter 2 numbers -->";
cin>>numb1>>numb2;
cout<<"GCD("<<numb1<<", "<<numb2<<") = "<<greatComDiv(numb1,numb2)<<endl;
}
例如,这是一个数字3和9的测试运行:
Enter 2 numbers -->3 9
GCD(3, 9) = 3
RUN SUCCESSFUL (total time: 3s)
另一个以数字100和-150进行的测试
Enter 2 numbers -->100 -150
GCD(100, -150) = 50
RUN SUCCESSFUL (total time: 3s)
这是又一个数字为0和-9的测试。
Enter 2 numbers -->0 -9
GCD(0, -9) = 9
RUN SUCCESSFUL (total time: 2s)
但是,这是当我输入0和0时发生的情况
Enter 2 numbers -->0 0
GCD(0, 0) = Undefined
-18165920
运行成功(总时间:2秒)
为什么-18165920出现在底部?它必须是if语句,因为这仅在0和0时才发生,但是我不明白我在做什么错。我将不胜感激。
答案 0 :(得分:0)
您应该在函数上返回一些信息。在您的特殊情况下,您不需要重新调整任何内容,这一定是打印该数字的原因。同样,在只返回一些结果的函数中打印某些内容也不是一个好习惯。试试这个:
int greatComDiv(int num1, int num2)
{
//The 2 lines below convert the numbers to their absolute value in case they are negative
num1 = abs(num1);
num2 = abs(num2);
//The if statement below takes care of the case that both numbers are zero the subsequent else statement performs the normal calculations if they are both not zero.
if( num1== 0 && num2 == 0)
{
return 0;
}
else
{
while(num2 > 0 )
{
num1%num2;
int tempNum = num1%num2;
num1 = num2;
num2 = tempNum;
}
return num1;
}
}
然后在主要代码中“捕获”异常:
int main()
{
int numb1, numb2, gcd;
cout<<"Enter 2 numbers -->";
cin>>numb1>>numb2;
gcd = greatComDiv(numb1,numb2);
if(gdc == 0) {
cout<<"GCD("<<numb1<<", "<<numb2<<") = undefined"<<endl;
} else {
cout<<"GCD("<<numb1<<", "<<numb2<<") = "<<gcd<<endl;
}
}