gpt4 book ai didi

c - 在 C 编程中使用数组、循环和条件

转载 作者:行者123 更新时间:2023-11-30 19:06:09 26 4
gpt4 key购买 nike

我试图解决的问题:

  • 向用户询问五个数字并将其存储在一个数组中。
  • 确定输入的最大数字和数组的平均值
  • 将使用 for 循环来解决此问题。

我为解决这个问题而编写的代码,但我不知道为什么会这样不工作。有人可以告诉我我做错了什么吗?

#include <stdio.h>

int main()
{
int i, n;
float arr[5], sum = 0, average;

printf("Please enter five numbers, separated by spaces!\n");
scanf("%d", &n);

//Stores numbers entered into an array
for(i = 0; i < n; i++)
{
printf("%d: ", i++);
scanf("%d", &arr[0]);


for(i = 1; i < n; i++)
{
if(arr[0] < arr[i])
arr[0] = arr[i];
}
printf("The highest of the five numbers is %d\n", arr[0]);

for(i = 0; i < n; i++)
{
printf("%d. Enter number: ", i+1);
scanf("%f", &arr[i]);
sum += arr[i];
}

average = sum / n;
printf("The average of the five numbers is %f\n", average);
}
}

最佳答案

#include <stdio.h>

int main()
{
int i, n;
float sum = 0, average;

printf("Please enter five numbers, separated by spaces!\n");
scanf("%d", &n);

float arr[n];

// no need to do i++ inside
//instead of saving all the values in arr[0], save it in arr[i]
//for loop needs to be closed here itself,which you had not done
for(i = 0; i < n; i++)
{
// printf("%d: ", i++); //no need to do this
scanf("%f", &arr[i]);
}
//initialize a max variable equal to first element of array
float max=arr[0];

//compare the max element with rest of the elements of the array and update it as you get any greater element than it
for(i = 1; i < n; i++)
{
if(max < arr[i])
max = arr[i];
}

//use %f format specifier for float
printf("The highest of the five numbers is %f\n", max);

for(i = 0; i < n; i++)
{
//no need to do here what u did since the value is already stored in array
//this for loop sums all the values present in array
sum += arr[i];
}

//takes out average and prints it
average = sum / n;
printf("The average of the five numbers is %f\n", average);

}

我已经在评论中指出了你的错误。希望有帮助!

关于c - 在 C 编程中使用数组、循环和条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48493837/

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