gpt4 book ai didi

c - C中的平均、最大和最小程序

转载 作者:太空狗 更新时间:2023-10-29 16:01:53 26 4
gpt4 key购买 nike

所以我用 C 编写代码,我需要编写代码,从用户那里获取 n 个数字,并找到它们的最小值、最大值、平均值和平方和作为它们的值。到目前为止,我有平均值和平方和部分,但最小值和最大值让我很头疼。

请记住,我处于非常初级的水平,我还没有达到数组。我只知道逻辑运算符、函数、循环以及 stdlib.h、math.h 和 stdio.h 库的使用。

这就是我目前所拥有的。当我在编译期间尝试放置 float 和 double 时,平均函数给了我很多问题,所以将它乘以 1.0 固定。我拥有一切,只有最小值和最大值。我一直将最后一个条目作为最大值,将 0 作为最小值。

#include<stdio.h>
int main()
{
float average;
int i, n, count=0, sum=0, squaresum=0, num, min, max;


printf("Please enter the number of numbers you wish to evaluate\n");
scanf_s("%d",&n);

printf("Please enter %d numbers\n",n);

while(count<n)
{
min=0;
max=0;

if(num>max)
max=num;
if(num<min)
min=num;

scanf_s("%d",&num);

sum = sum+num;
squaresum = squaresum + (num*num);

count++;
}
average = 1.0*sum/n;

printf("Your average is %.2f\n",average);
printf("The sum of your squares is %d\n",squaresum);



printf("Your maximum number is %d\n",max);
printf("Your minimum number is %d\n",min);

return(0);
}

最佳答案

您的算法不太正确。下面是正确的实现:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

int main(void)
{
float average;
int n, num, count = 0, sum = 0, squaresum = 0;
int min = INT_MAX, max = INT_MIN;
bool gotAnswer = false;

/* Don't Let User Enter Wrong Input */
while(!gotAnswer)
{
printf("Please enter the number of numbers you wish to evaluate: ");
if(scanf_s("%d", &n) != 1)
{
/* User Entered Wrong Input; Clean Up stdin Stream*/
while(getchar() != '\n')
{
continue;
}
}
else
{
/* User Input Was Good */
gotAnswer = true;
}
}

/* Clear stdin Stream Just In Case */
while(getchar() != '\n')
continue;

while(count < n)
{
/* Don't Let User Enter Wrong Input */
gotAnswer = false;
printf("Enter number %d: ", count + 1);
if(scanf_s("%d", &num) != 1)
{
/* User Entered Wrong Input; Clean Up stdin Stream */
while(getchar() != '\n')
continue;

/* Let User Try Again */
continue;
}
else
{
/* User Input Was Correct */
gotAnswer = true;

/* Clear stdin Stream Just In Case */
while(getchar() != '\n')
continue;
}

if(num > max)
max = num;
if(num < min)
min = num;

sum += num;
squaresum += num * num;
count++;
}

average = 1.0 * sum / n;

printf("Your average is %.2f\n", average);
printf("The sum of your squares is %d\n", squaresum);
printf("Your maximum number is %d\n", max);
printf("Your minimum number is %d\n", min);

system("pause");
return 0;
}

我添加了错误检查和恢复。如果您对逻辑有任何疑问,请询问。

关于c - C中的平均、最大和最小程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20769834/

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