while 循环 c++ 中的非法指令

Illegal instruction in while loop c++

本文关键字:非法 指令 循环 c++ while      更新时间:2023-10-16

我被指派编写一个简化有理数的程序。我想做的是计算 gcd,然后将数字除以 gcd。但是程序返回一个非常奇怪的错误。

代码:

void read_rational(int& num, int& den) {
char bar;
if (cin >> num >> bar >> den) {
cout << "hi";
int a = num;
int b = den;
while (b != 0) {
int r = a%b;
a = b;
b = r;
}
num /= b;
den /= b;
}
}
INPUT: 10/2  OUTPUT: Illegal instruction (core dumped)
INPUT: 90/8  OUTPUT: Illegal instruction (core dumped)

我尝试注释掉脚本的某些部分。程序似乎仅在存在 while 循环时才崩溃。但我看不出它有什么问题。

事实上,问题是while循环。完成后,b实际上是 0,因此之后的除法会引发这些错误。 我认为你想要的是a而不是b.