gpt4 book ai didi

c - 为什么这个程序无法在(4*4)(或更高)数组中找到鞍点?

转载 作者:行者123 更新时间:2023-11-30 16:59:16 25 4
gpt4 key购买 nike

  #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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com