gpt-3.5-turbo-0301· OpenAI
WildChat-4.8M (AI2)
用C++写代码 Integer类,包含一个int型成员,一个构造函数Integer,一个成员函数gcd【问题描述】…
- User
用C++写代码 Integer类,包含一个int型成员,一个构造函数Integer,一个成员函数gcd【问题描述】 设计一个Integer类,包含一个int型成员,一个构造函数integer(用于初始化参数),一个成员函数gcd(计算最大公约数),输入两个正整数a和b,得到其最大公约数。 参考主函数 int main0 ( int a b: cin >> a >> b Integer A(a): integer B(b): cout << A.gcd(B) << endl retum 0: 【输入形式】【输出形式】【样例输入】【样例输出】0 12 【样例输入】 input error【样例输出】15 12 【样例说明】3
- Assistant
代码如下:
#include using namespace std;
class Integer { private: int num; public: Integer(int n): num(n) {} // 构造函数
int gcd(Integer b) { // 最大公约数函数 int a = num; while (b.num != 0) { int temp = a % b.num; a = b.num; b.num = temp; } return a; }};
int main() { int a, b; if (!(cin >> a >> b)) { // 输入异常处理 cout << "input error" << endl; return 0; } Integer A(a), B(b); cout << A.gcd(B) << endl; return 0; }