设计复数库,实现基本的复数加减乘除运算。
输入时只需分别键入实部和虚部,以空格分割,两个复数之间用运算符分隔;输出时按a+bi的格式在屏幕上打印结果。参加样例输入和样例输出。
注意考虑特殊情况,无法计算时输出字符串”error”。
样例输入
2 4 * -3 2
样例输出
-14-8i
样例输入
3 -2 + -1 3
样例输出
2+1i
分析:除法的时候有点麻烦,结果要变成浮点型,因为测试用例的答案是统一输出一位有效数字的。。所以0.123输出0.1 1.000输出1。。。我用了cout的setprecision控制输出的有效数字个数~
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 |
#include <iostream> #include <iomanip> using namespace std; void add(int a, int b, int m, int n); void min(int a, int b, int m, int n); void multi(int a, int b, int m, int n); void div1(int a, int b, int m, int n); int main() { int a,b,m,n; char c; cin >> a >> b; cin >> c; cin >> m >> n; switch(c) { case '+': add(a, b, m, n); break; case '-': min(a, b, m, n); break; case '*': multi(a, b, m, n); break; case '/': div1(a, b, m, n); break; } return 0; } void add(int a, int b, int m, int n) { int l, r; l = a + m; r = b + n; if (l != 0){ if (r != 0) { if (r > 0) cout << l << "+" << r << "i"; else cout << l << r << "i"; } else { cout << l; } } else { if (r != 0) { cout << r << "i"; } else { cout << 0; } } } void min(int a, int b, int m, int n) { int l, r; l = a - m; r = b - n; if (l != 0) { if (r != 0) { if (r > 0) cout << l << "+" << r << "i"; else cout << l << r << "i"; } else { cout << l; } } else { if (r != 0) { cout << r << "i"; } else { cout << 0; } } } void multi(int a, int b, int m, int n) { int l, r; l = a * m - b * n; r = a * n + b * m; if (l != 0) { if (r != 0) { if (r > 0) cout << l << "+" << r << "i"; else cout << l << r << "i"; } else { cout << l; } } else { if (r != 0) { cout << r << "i"; } else { cout << 0; } } } void div1(int a, int b, int m, int n) { if (m == 0 && n == 0) { cout << "error"; } else { double l, r; l = (double)(a * m + b * n) / (m * m + n * n); r = (double)(b * m - a * n) / (m * m + n * n); if (l != 0) { if (r != 0) { if (r > 0) { cout << setprecision(1) << l << "+" << r << endl; } else { cout << setprecision(1) << l << r << "i" << endl; } } else { cout << setprecision(1) << l << endl; } } else { if (r != 0) { cout << setprecision(1) << r << "i" << endl; } else { cout << 0; } } } } |
❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼