#include <stdio.h> #include <stdlib.h> #define ROW 6 #define COL 6 int main() { int score[ROW][COL]; int cards[6]; int i, j, k, num, dir, total_score; // input score table for (i = 0; i < ROW; i++) { for (j = 0; j < COL; j++) { scanf("%d", &score[i][j]); } } // input cards for (i = 0; i < 6; i++) { scanf("%d", &cards[i]); } // input and process each customer for (k = 0; k < 3; k++) { total_score = 0; scanf("%d %d", &num, &dir); // calculate score if (cards[num-1] == 0) { printf("Invalid card number!\n"); continue; } if (dir == 1) { for (i = 0; i < COL; i++) { total_score += score[num-1][i]; } } else if (dir == 2) { for (i = 0; i < ROW; i++) { total_score += score[i][num-1]; } } else { printf("Invalid direction!\n"); continue; } printf("%d\n", total_score); } return 0; } 改进上述代码
时间: 2024-02-05 16:03:27 浏览: 56
上述代码已经可以正常运行,但是可以进行一些改进:
1. 可以增加注释,让代码更易读懂。
2. 可以在输入时对输入数据进行合法性检查,比如积分表中的数字应该在1~100之间,卡牌数字应该在0~6之间,等等。
3. 可以将代码拆分成多个函数,让主函数更加简洁明了。
4. 可以增加错误处理机制,比如输入数据格式错误时给出提示,让程序更加健壮。
下面是改进后的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#define ROW 6
#define COL 6
// 检查输入的数字是否合法,若不合法则返回0,否则返回1
int isValidNumber(int num, int min, int max)
{
if (num < min || num > max)
{
return 0;
}
return 1;
}
// 读取积分表
void readScoreTable(int score[ROW][COL])
{
int i, j;
printf("Please input the score table:\n");
for (i = 0; i < ROW; i++)
{
for (j = 0; j < COL; j++)
{
scanf("%d", &score[i][j]);
if (!isValidNumber(score[i][j], 1, 100))
{
printf("Invalid input: score should be between 1 and 100!\n");
exit(1);
}
}
}
}
// 读取卡牌
void readCards(int cards[6])
{
int i;
printf("Please input the cards:\n");
for (i = 0; i < 6; i++)
{
scanf("%d", &cards[i]);
if (!isValidNumber(cards[i], 0, 6))
{
printf("Invalid input: card number should be between 0 and 6!\n");
exit(1);
}
}
}
// 计算得分
int calculateScore(int score[ROW][COL], int cards[6], int num, int dir)
{
int i, total_score = 0;
if (cards[num-1] == 0)
{
printf("Invalid input: card number %d is hidden!\n", num);
return 0;
}
if (dir == 1)
{
for (i = 0; i < COL; i++)
{
total_score += score[num-1][i];
}
}
else if (dir == 2)
{
for (i = 0; i < ROW; i++)
{
total_score += score[i][num-1];
}
}
else
{
printf("Invalid input: direction should be 1 or 2!\n");
return 0;
}
return total_score;
}
// 处理每个顾客的输入和输出
void processCustomer(int score[ROW][COL], int cards[6])
{
int i, num, dir, total_score;
for (i = 0; i < 3; i++)
{
printf("Please input the card number and direction for customer %d:\n", i+1);
scanf("%d %d", &num, &dir);
total_score = calculateScore(score, cards, num, dir);
printf("Customer %d's score is %d\n", i+1, total_score);
}
}
int main()
{
int score[ROW][COL];
int cards[6];
readScoreTable(score);
readCards(cards);
processCustomer(score, cards);
return 0;
}
```
阅读全文