我必須找到一種方法來顯示數組中的最大和最小數字,數組的大小爲100,並且不會超過這個數字,並且不需要用於輸入驗證。程序會一直詢問輸入,直到遇到0,並且它也會被添加到數組中。如何在數組中找到最大和最小數字c
我有一切想通了,除了如何跟蹤哪些是最大和最小的價值。我會很感激,如果有人可以修復我的代碼或顯示我。我遇到的另一個問題是獲取循環終止並在輸入等於0時在while循環內執行最大/最小計算。
/*
============================================================================
Name : test.c
Author :
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#define n 100
int main(void){
int numbers[n];
int i = 1;
int j;
int input;
int maxvalue;
int minvalue;
printf("Enter the next array element>");
input = scanf("%d", &numbers[100]);
while (input != 0){
numbers[i] = input;
i++;
printf("Enter the next array element, while loop>");
input = scanf("%d", &numbers[n]);
if (input == 0){
printf("Enter the next array element, if loop");
numbers[i] = 0;
for (j =2;j <= i; j++){
minvalue = numbers[1];
j++;
if (numbers[j] > minvalue){
maxvalue = numbers[j] ;
}
else{
minvalue = numbers[j] ;
}
}
}
}
printf("%f\t", maxvalue);
printf("%f\n", minvalue);
}
編輯:我把你的所有建議和編輯我的代碼。這是我的代碼如下。但是,它的輸出不是我所期望的。
#include <stdio.h>
#include <stdlib.h>
#define N 100
int main(void){
int numbers[N];
int i = 0;
int j;
int input;
int maxvalue;
int minvalue;
printf("Enter the next array element>");
scanf("%d", &input);
while (input != 0){
numbers[i] = input;
i++;
if (input == 0){
i++;
numbers[i] = 0;
minvalue = numbers[0];
maxvalue = numbers[0];
for (j=0;j<=i-1;j++){
if (minvalue >= numbers[j]){
minvalue = numbers[j];
}else if (maxvalue <= numbers[j]){
maxvalue = numbers[j];
}
}
/* min = value of first array element
max = value of first array element
begin loop for each array element, index = 0 to (n-1)
--- if array element value is less than min, set min to this value
--- if array element value is more than max, set max to this value
increment index and repeat loop til last index is completed
average = sum/number of elements (n).
max and min will hold their correct values.*/
}
printf("Enter the next array element, while loop>");
scanf("%d", &input);
}
printf("%d\t", maxvalue);
printf("%d", minvalue);
}
這是輸出,我得到了!有人可以爲我解決這個問題嗎?
最後編輯:我解決了這個我自己。我將最小/最大值檢查放在主WHILE循環之外,這允許輸入0輸入到數組中。
#include <stdio.h>
#include <stdlib.h>
#define N 100
int main(void){
int numbers[N];
int i = 0;
int j;
int input;
int maxvalue =1;
int minvalue = 1;
printf("Enter the next array element>");
scanf("%d", &input);
minvalue = input;
maxvalue = input;
while (input != 0){
numbers[i] = input;
++i;
printf("Enter the next array element>");
scanf("%d", &input);
if (input == 0){
numbers[i] = 0;
++i;
}
}
for (j =0;j<i;j++){
if (numbers[j] >= maxvalue){
maxvalue = numbers[j];
}
if(numbers[j] < minvalue){
minvalue = numbers[j];
}
}
printf("%d\t", maxvalue);
printf("%d\n", minvalue);
}
在C,數組索引從0開始發生什麼。你也許可以在沒有任何錯誤的情況下使用1,因爲你在本地使用它,所以你只是一直跳過第一個元素,但它會嘮叨每一個C程序員。 – tia 2010-09-26 07:24:15
嘗試對n等預處理器常量使用大寫字母,表明它們與變量不同。 – 2010-09-26 07:45:05
請仔細檢查你的代碼 – pmg 2010-09-27 07:06:40