#include <stdio.h>
int main(void)
{
int n, m, i, j, k, q, r, maxr = 0, state = 0, count= 0;
puts("Enter two numbers represents two dimensional array, N * M");
puts("This program will find the saddle points");
scanf("%d %d", &n, &m);
int ar[n][m];
for (j = 0; j < m; j++)
{
for (i = 0; i < n; i++)
{
puts("Enter the number in array");
scanf("%d", &ar[i][j]); //store the number form user
printf("Array accepted %d, and this number's location is [%d][%d]\n", ar[i][j], i, j);
}
}
for (int j = 0; j < m; j++) //print the two dimensional array
{
for (int i = 0; i < n; i++)
{
printf("%3d", ar[i][j]);
}
putchar('\n');
}
for (int j = 0; j < n; j++) //find the saddle point
{
for (int i = 0; i < m; i++)
{
if(ar[i][j] > maxr) //compare the number is i row until find the biggest
{
maxr = ar[i][j];
q = i;
r = j;
}
else
continue;
}
for (int k = 0; k < n; k++)
{
if (ar[q][k] < maxr)
{
state = 0;
break;
}
if (ar[q][k] > maxr)
{
r = k;
state = 1;
continue;
}
if (ar[q][k] == maxr)
{
state = 1;
continue;
}
}
count++;
if (state == 1)
printf("The saddle point is (%d), location is [%d][%d]\n", ar[q][k], q, k);
else
printf("The %d row does not contain a saddle point\n", count);
}
}
该程序旨在查找鞍点。二维阵列中的鞍点表示行中最大的点,但列中最小的点。例如,第一排1、2,第二排3、4,则鞍点为2。
我遇到的问题是,该程序可以找到3 * 3阵列的鞍点,但是找不到4 * 4(或更高)阵列的鞍点。
例如,
2, 3, 9, 5
6, 7, 8, 3
0, 5, 7, 5
2, 1, 8, 3
然后,鞍点是第3行第3列,第7列。但是该程序找不到。
那么问题是什么,逻辑问题呢?但我可以找到2 * 2或3 * 3阵列的鞍点。
最佳答案
您应在循环内设置max的重置值。
这将在每个列中找到一个鞍点。
#include <stdio.h>
int main(void){
int n, m, i, j, k,max;
puts("Enter two numbers represents two dimensional array, N * M");
puts("This program will find the saddle points");
scanf("%d %d", &n, &m);
int ar[n][m];
for (j = 0; j < n; j++)
for (i = 0; i < m; i++){
puts("Enter the number in array");
scanf("%d", &ar[j][i]); //store the number form user
printf("Array accepted %d, and this number's location is [%d][%d]\n", ar[i][j], i, j);
}
for (j = 0; j < n; j++){ //print the two dimensional array
for (i = 0; i < m; i++)
printf("%3d", ar[j][i]);
putchar('\n');
}
for (int i = 0; i < n; i++){ //for each row
max=0;
for (j = 1; j < m; j++) //find biggest in the row
if(ar[i][j] > ar[i][max])
max=j;
for (k=0; k < n; k++) // if there are bigger element than this in that column, break
if (ar[k][max] < ar[i][max])
break;
if(k==n) // if there were no bigger elements in the column
printf("The saddle point is (%d), location is [%d][%d]\n", ar[i][max], i+1, max+1);
}
}
关于c - 为什么此程序无法在(4 * 4)(或更高)数组中找到鞍点?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38268847/