使用C语言输入一个全是个位数的3*3的矩阵,并判断其中是否有相同的数字
时间: 2024-09-19 20:15:29 浏览: 51
在C语言中,你可以编写一个简单的程序来输入一个由个位数构成的3x3矩阵,并检查是否存在相同的数字。下面是一个示例代码:
```c
#include <stdio.h>
// 函数用来判断矩阵中有无重复的数字
int has_duplicate(int matrix[3][3]) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
// 获取当前数字
int digit = matrix[i][j];
// 检查是否已存在
for (int k = 0; k < 3; k++) {
for (int l = 0; l < 3; l++) {
if (matrix[k][l] == digit && k != i && l != j) {
return 1; // 找到重复,返回1
}
}
}
}
}
return 0; // 没有找到重复,返回0
}
int main() {
int matrix[3][3];
printf("请输入一个3x3的个位数矩阵(数字范围1-9):\n");
// 读取矩阵
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
scanf("%d", &matrix[i][j]);
if (matrix[i][j] < 1 || matrix[i][j] > 9) {
printf("输入错误!数字必须在1到9之间。\n");
return 1;
}
}
}
if (has_duplicate(matrix)) {
printf("矩阵中有相同的数字。\n");
} else {
printf("矩阵中没有相同的数字。\n");
}
return 0;
}
```
这个程序首先定义一个`has_duplicate`函数,遍历矩阵的每个位置,将数字与除自身之外的所有其他位置的数字进行比较,如果找到相同的则返回1。主函数中读取用户的输入并调用`has_duplicate`函数,根据返回结果打印相应的消息。
阅读全文
相关推荐


















