我正在使用repl.it来编写我的C ++。到目前为止,我已经了解了条件,循环和函数。现在我正在尝试编写一个输入两个整数的程序,并找到最小公倍数和最大公分母。到目前为止,我已经编写了大部分代码,但是存在问题。
“以非零状态退出”
#include <iostream>
using namespace std;
int main()
{
int number1 = 0;
int number2 = 0;
int calc = 0;
int lcm = 0;
cout << "Give me two integers, and I will calculate the Least Common Multiple and the Greatest Common Divisor." << endl;
while (number1 <= 0) {
cout << "Enter your first number. Cant be negative" << endl;
cin >> number1; }
while (number2 <= 0) {
cout << "Enter your second number. Cant be negative" << endl;
cin >> number2; }
while(number2 != 0) { ///Greatest Common Divisor
calc = number1 % number2;
lcm = (number1*number2) / calc;
number1 = number2;
number2 = calc;
}
cout << "Least Common Multiple is " << lcm << endl;
cout << "Greatest Common divisor is " << number1 << endl;
}
所以我不确定这是一个语法错误,还是因为repl.it,但我真的很难弄清楚这一点。
由于
答案 0 :(得分:1)
while循环在循环结束时检查number2值,但是当你计算calc时,有时这个值为零,那么在下一步中程序退出时除以零异常。您可以通过在计算calc变量后将此行添加到代码来防止此问题:
if (calc == 0 ) break;
另外,您的代码无法正常工作,例如set number1 = 30和number2 = 18!
我使用二进制方法计算GCD,然后使用GCD计算LCM。
#include <iostream>
#include <math.h> // for pow(2,d)
using namespace std;
int main()
{
int gcd, lcm, a, b, g, number1 = 0, number2 = 0, d=0;
cout << "Give me two integers, and I will calculate the Greatest Common Divisor and the Least Common Multiple." << endl;
while (number1 <= 0) {
cout << "Enter your first number. Cant be negative" << endl;
cin >> number1;
}
// using binary method to calculating GCD: https://en.wikipedia.org/wiki/Greatest_common_divisor
while (number2 <= 0) {
cout << "Enter your second number. Cant be negative" << endl;
cin >> number2;
}
a = number1;
b = number2;
while (((a%2)==0) && ((b%2)==0)) {
a = a/2;
b = b/2;
d = d+1;
}
while (a != b) {
if ((a%2) == 0) {
a = a/2;
} else if ((b%2)==0) {
b = b/2;
} else if (a>b) {
a = (a-b) /2;
} else {
b = (b-a)/2;
}
}
g = a;
cout << "\ng: " << g << "\td: " << d << "\tpower(2,d): " << pow(2,d);
gcd = g * pow(2,d); // power(2,d) with math.h library
lcm = (number1*number2)/gcd; // according to LCM(a,b) = (a*b)/GCD(a,b)
cout << "\nGreatest Common Divisor is " << gcd << " and Least Common Multiple is " << lcm << endl;
}
答案 1 :(得分:0)
首先,您需要检查哪个数字更大,因为如果您设置number1=18
和number2=30
,则number1%number2
将为18,然后您会看到它的位置 - 到错误的输出。此外,Hossein Nazari建议的修复可以避免异常,但如果您遵循该修复,则GCD将存储在number2
中。例如30和18:
30%18 = 12
calc = 12
if(calc==0) break;
(lcm routine)
number1 = 18
number2 = 12
18%12 = 6
calc=6
if(calc==0) break;
(lcm routine)
number1 = 12
number2 = 6
12%6=0
calc=0
if(calc==0) break;
<done>
我宁愿完全从你的循环中删除lcm计算,在这种情况下,你按照计划在number1
得到你的GCD,然后只按公式(number1*number2)/GCD
计算LCM,这将是30*18/6 = 90;
答案 2 :(得分:-1)
嗨,只需更改这两个数据类型
float calc = 0;
float lcm = 0;
嗨@Cheers和hth,我在这里执行了代码https://www.tutorialspoint.com/compile_cpp11_online.php,并得到了这个异常 - 浮点异常,
在我将数据类型从int更改为float后,我得到了这个值
输入您的第一个号码。不能为负
10个
输入您的第二个号码。不能为负
20个
最小公倍数是inf
最大公约数是10