因此,我正在尝试制作一个简单的程序,该程序读取值和ID号的整数,因此输出将是该值及其maxID minID号的最小最大值。输入文件的第一个整数将指示要在循环中读取多少输入。我的程序编译没有问题,最小最小输出正确,但是ID号输出错误。谁能帮助我诊断这个问题?对不起我的愚蠢问题,我是编程新手。谢谢。
#include <stdio.h>
int main(){
int val[100],id[100];
int i, max, min, size, idmax, idmin,minindex,maxindex;
printf("Enter how many IDs: ");
scanf("%d", &size);
printf("Enter ID numbers and values:\n");
for(i=0; i<size; i++)
{
scanf("%d %d", &id[i], &val[i]);
}
max = min = val[0];
for(i=1; i<size; i++)
{
if(val[i] > max)
{
max = val[i];
maxindex = i;
for(i=0;i<size;i++){
if(id[i]==maxindex){
idmax=id[i];
}
}
}
if(val[i] < min)
{
min = val[i];
minindex = i;
for(i=0;i<size;i++){
if(id[i]==minindex){
idmin=id[i];
}
}
}
}
printf("Max number = %d with ID number = %d\n", max, idmax);
printf("Min number = %d with ID number = %d\n", min, idmin);
return 0;
}
您使问题变得比实际复杂。通过;列表运行时,只要更新相应的idmax
或idmin
,就可以简单地更新max
或min
值:
#include <stdio.h>
int main() {
int val[100], id[100];
int i, max, min, size, idmax, idmin;/// No longer need these: minindex, maxindex;
printf("Enter how many IDs: ");
scanf("%d", &size);
printf("Enter ID numbers and values:\n");
for (i = 0; i < size; i++) {
scanf("%d %d", &id[i], &val[i]);
}
max = min = val[0];
idmin = idmax = id[0];/// Initialize IDs similarly to min and max
for (i = 1; i < size; i++) {
if (val[i] > max) {
max = val[i];
idmax = id[i];/// Only need to change this when max changes
}
if (val[i] < min) {
min = val[i];
idmin = id[i];/// Only need to change this when min changes
}
}
printf("Max number = %d with ID number = %d\n", max, idmax);
printf("Min number = %d with ID number = %d\n", min, idmin);
return 0;
}