我尝试制作程序以找到任意两个数字的最低公倍数。我已经完成了大部分工作,但我的程序会打印所有常见的倍数,从1-1000000而不是第一个。如何使其仅打印第一个 ?
#include <iostream>
using namespace std;
int main() {
cout << "Find the lowest common multiple of two numbers, just enter them one after the other" << endl;
int firstNum;
int secondNum;
cin >> firstNum;
cin >> secondNum;
int i;
for (i = 1; i < 1000001; i++) {
if (i % firstNum == 0 && i % secondNum == 0) {
cout << "these two number's LCM is" << i << endl;
}
}
system("pause");
return 0;
}
答案 0 :(得分:1)
您可以添加break
来结束循环。在您的情况下,您希望在if
声明的末尾添加它:
for (i = 1; i < 1000001; i++) {
if (i % firstNum == 0 && i % secondNum == 0) {
cout << "these two number's LCM is" << i << endl;
break;
}
}
答案 1 :(得分:0)
您的问题是其他人提到的break
声明。
但更好的解决方案:lcm
在C ++ 17中标准化了!所以你可以这样做:
cout << lcm(firstNum, secondNum) << endl;
如果您无法访问C ++ 17,则namespace experimental
Dim Cnt As Variant
Dim oCell As Object
Cnt = 0 '
With ie.Document.all
For Each oCell In .tags("td")
If oCell.src = "../img/DL.jpg" Then
ocell.click
ocell.fireevent("submit") 'aircode, might have to be moved.
Exit For
End If
Cnt = Cnt + 1
Next oCell
End With
已提供此功能:http://en.cppreference.com/w/cpp/experimental/lcm
答案 2 :(得分:0)
找到第一个你需要离开for循环后,这就是它继续打印其他值的原因。
for (i = 1; i < 1000001; i++) {
if (i % firstNum == 0 && i % secondNum == 0) {
cout << "these two number's LCM is" << i << endl;
break;
}
}