优化这段代码void caozuo(unsigned int c) { n = c; switch (c) { case 0: { n = n * 10 + 1; shuzi(n); break; } case 1: { n = n * 10 + 2; shuzi(n); break; } case 2: { n = n * 10 + 3; shuzi(n); break; } case 3: { jisuan(); flag = '+'; break; } case 4: { n = n * 10 + 4; shuzi(n); break; } case 5: { n = n * 10 + 5; shuzi(n); break; } case 6: { n = n * 10 + 6; shuzi(n); break; } case 7: { jisuan(); flag = '-'; break; } case 8: { n = n * 10 + 7; shuzi(n); break; } case 9: n = n * 10 + 8; shuzi(n); break; case 10: { n = n * 10 + 9; shuzi(n); break; } case 11: { jisuan(); flag = '*'; break; } case 12: { n = n * 10 + 0; shuzi(n); break; } case 13: { for (i = 0; i < 4; i++) DispBuf[i] = 0; temp = 0; flag = ' '; n = 0; break; } case 14: { jisuan(); break; } case 15: { jisuan(); flag = '/'; break; } } }
时间: 2024-02-14 22:12:39 浏览: 118
可以使用一个数组来存储对应的操作,这样可以避免使用 switch 语句,从而提高代码的效率和可读性。优化后的代码如下:
void caozuo(unsigned int c) {
static const int caozuoArray[16] = {1, 2, 3, '+', 4, 5, 6, '-', 7, 8, 9, '*', 0, 'C', '=', '/'};
n = c;
if (c >= 0 && c <= 15) {
int op = caozuoArray[c];
if (op >= 0 && op <= 9) {
n = n * 10 + op;
shuzi(n);
} else if (op == 'C') {
for (i = 0; i < 4; i++) {
DispBuf[i] = 0;
}
temp = 0;
flag = ' ';
n = 0;
} else if (op == '=' || op == '+' || op == '-' || op == '*' || op == '/') {
jisuan();
flag = op;
}
}
}
这样可以使代码更加简洁和易读,同时也可以提高代码的执行效率。
阅读全文