[英]Finding the average, maximum, minimum value of array in c
我正在嘗試獲取數組的最小值和最大值。 由用戶創建的數組。 我不斷收到Segmentation fault (core dumped)
。 我不知道我在哪里做錯了。
#include <stdio.h>
int main(void){
int n, i;
double sum = 0.0, array[n], avg;
printf("Enter the size of the array:");
scanf("%d", &n);
for (i=0; i<n; ++i){
printf("Enter the number for position %d: ", i + 1);
scanf("%i", &n);
sum += n;
}
avg = (double) sum / n;
printf("Average = %.2f\n", avg);
double largest = array[0], smallest = array[0];
for (i = 0; i < n; i++){
if (array[i] > largest)
{
largest = array[i];
}
else if (array[i] < smallest)
{
smallest = array[i];
}
}
printf("The smallest is %lf and the largest is %lf!\n", smallest, largest);
}
編輯:解決這個問題后,我看到我也無法獲得最小值和最大值。 我一直為兩者提供0.000000
。 我該如何解決? 我嘗試改變double
float
但沒有工作..
您在初始化n
之前編寫了array[n]
。 這將調用未定義的行為來使用未初始化的非靜態局部變量n
的(不確定的)值。
分配數組必須在讀取n
之后。 它會是這樣的:
int n, i;
double sum = 0.0, avg;
printf("Enter the size of the array:");
scanf("%d", &n);
double array[n];
@MikeCAT 完全正確...
但是,如果您使用 c89 或 c90 標准,您將無法從用戶那里獲取數據然后聲明數組。 當您嘗試編譯它時可能會收到此消息:
ISO C90/C89 forbids mixed declarations and code in C
您將能夠做的是使用 malloc 或 calloc 動態分配它。
我看到你沒有使用這個標准,但我還是寫了它,所以如果有人會看到這個,它可能會阻止一個可能的問題..
如果您不知道您使用的是哪個 c 標准,請檢查您的編譯說明是否有“-ansi”或“std=c99”標志,這意味着您使用的是 c89 或 c90 標准。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.