为什么它没有向我展示最大的共同点?
Why it doesn't show me the greatest common divison?
当我尝试启动程序时,它不起作用并且没有显示任何错误。为什么?
#include <iostream>
using namespace std;
int main()
{
unsigned a,b;
cout<<"a=";
cin>>a;
cout<<"b=";
cin>>b;
{
while(a!=b)
{
if(a>b)
(a==a-b);
else
(b==b-a);
}
}
cout<<"cmmdc=",a;
return 0;
}
将a==a-b
替换为 a=a-b
。
将b==b-a
替换为 b=b-a
。
运算符==
是比较,它不会修改其参数。运算符=
赋值,它将左参数修改为其右参数的值。
将cout<<"cmmdc=",a
替换为 cout<<"cmmdc="<<a
,否则不会打印a
。
即使在将
==
s 更改为 =
s 之后,如果 a
中的任何一个(但不是两个)b
都是 0,你也会得到一个无限循环。若要避免这种情况,请改用此循环:
while (b != 0) {
const unsigned olda = a;
a = b;
b = olda % b;
}
// GCD is now in a.
这是找到两个数字的 gcd 的最简单方法:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int a,b;
cout<<"a = ";
cin>>a;
cout<<"b = ";
cin>>b;
cout<<"GCD = " << __gcd(a,b);
}
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 为什么在全局范围内使用"extern int a"似乎不行?
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 为什么会发生堆损坏
- 为什么使用 "this" 指针调用派生成员函数?
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 为什么比较运算符如此快速
- 为什么 Serial.println(<char[]>);返回随机字符?
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 为什么不;名字在地图上是按顺序排列的吗
- 我的字符计数代码计算错误.为什么
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 为什么 std::unique 不调用 std::sort?
- 既然存在危险,为什么项目要使用-I include开关
- 为什么它没有向我展示最大的共同点?