swc_swc @ 2024-11-29 22:10:24
请大佬帮忙改一下代码 题目:请编写一段有关计算器的代码要求:实现最基础的加减乘除运算,并能在各种进制间转换,并能计算日期的c++代码
#include <bits/stdc++.h>
using namespace std;
// 执行基本运算
double calc(double num1, char op, double num2) {
switch (op) {
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
if (num2 == 0) {
cerr << "错误:除数不能为零!" << endl;
return 0;
}
return num1 / num2;
default:
cerr << "错误:无效的运算符!" << endl;
return 0;
}
}
// 十进制转其他进制
string decToOtherBase(int decimal, int targetBase) {
if (decimal == 0) return "0";
string result = "";
while (decimal > 0) {
int rem = decimal % targetBase;
result = (rem < 10? to_string(rem) : static_cast<char>(rem - 10 + 'A')) + result;
decimal /= targetBase;
}
return result;
}
// 其他进制转十进制
int otherBaseToDec(string number, int sourceBase) {
int result = 0;
int power = 1;
for (int i = number.length() - 1; i >= 0; --i) {
int digit = (number[i] >= '0' && number[i] <= '9')? number[i] - '0' : number[i] - 'A' + 10;
result += digit * power;
power *= sourceBase;
}
return result;
}
// 计算日期
void calcDate(int days) {
time_t curTime = time(nullptr);
tm* curDate = localtime(&curTime);
curDate->tm_mday += days;
time_t newTime = mktime(curDate);
char buffer[80];
strftime(buffer, sizeof(buffer), "%Y-%m-%d", curDate);
cout << "增加 " << days << " 天后的日期:" << buffer << endl;
}
int main() {
// 基本运算示例
double num1, num2;
char op;
cout << "请输入第一个数、运算符、第二个数(例如:2 + 3):";
cin >> num1 >> op >> num2;
double result = calc(num1, op, num2);
cout << "结果:" << result << endl;
// 进制转换示例
int decimalNum;
int targetBase;
cout << "请输入要转换的十进制数:";
cin >> decimalNum;
cout << "请输入要转换到的进制(2 - 16):";
cin >> targetBase;
string converted = decToOtherBase(decimalNum, targetBase);
cout << decimalNum << " 转成 " << targetBase << " 进制为:" << converted << endl;
string numberInBase;
int sourceBase;
cout << "请输入一个指定进制(2 - 16)下的数来转换为十进制:";
cin >> numberInBase;
cout << "请输入该数的进制:";
cin >> sourceBase;
int decimalResult = otherBaseToDec(numberInBase, sourceBase);
cout << numberInBase << " 在 " << sourceBase << " 进制下转成十进制为:" << decimalResult << endl;
// 日期计算示例
int days;
cout << "请输入要在当前日期上增加的天数:";
cin >> days;
calcDate(days);
return 0;
}
谢谢啦!!