童
2024-06-02 22:15:53
发布于:广东
处理负数的,时间不够,只能写这么点,主要chat他不靠谱了。>_<!!!
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 100005;
char A[MAXN], B[MAXN];
struct node {
short a[MAXN] = {0};
int len = 0, f = 1; // f 用来表示正负,1 表示正,-1 表示负
void _init(char *A) {
len = strlen(A);
for (int i = 0; i < len; i++) {
a[i] = A[len - i - 1] - '0';
}
// 如果第一个字符是负号,则设置f为-1
if (A[0] == '-') {
f = -1;
len--;
memmove(a, a + 1, sizeof(short) * len);
}
}
void print() {
if (f == -1) cout << "-";
for (int i = len - 1; i >= 0; i--) {
cout << a[i];
}
cout << endl;
}
// 其他操作符重载函数保持不变,需要添加负数处理逻辑
// ...
};
// 处理负数的辅助函数
node handle_negative(node &a, node &b, char operation) {
node result;
bool a_negative = a.f == -1, b_negative = b.f == -1;
switch (operation) {
case 'A': // 加法
result = a_negative ^ b_negative ? (a - b) : (a + b);
break;
case 'B': // 减法
result = a_negative ^ b_negative ? (a + b) : (a - b);
break;
case 'C': // 乘法
result = a * b;
result.f = a_negative ^ b_negative ? -1 : 1;
break;
case 'D': // 除法
// 负数除法需要特殊处理
if (a_negative != b_negative) {
result = a / b;
result.f = -1;
} else {
result = a / b;
result.f = 1;
}
break;
// ... 其他操作的处理
}
return result;
}
void __init() {
node a, b, c;
char operation;
cout << "请输入第一个数:";
cin >> A;
cout << "请输入第二个数:";
cin >> B;
cout << "请选择操作(A加, B减, C乘, D除): ";
cin >> operation;
a._init(A);
b._init(B);
c = handle_negative(a, b, operation);
c.print();
}
void choose() {
char choice;
do {
__init();
cout << "\n还要继续运算吗?(y/n): ";
cin >> choice;
} while (choice == 'y' || choice == 'Y');
}
int main() {
choose();
return 0;
}
全部评论 1
算了😂反正我都有提示了应该不会还有人作死
2024-06-05 来自 广东
0
有帮助,赞一个