我对Objective C相当陌生,并且有一个任务要求我接受用户的一系列整数并从中提供5条信息:
- 输入数量
- 输入的总和
- 输入的平均值
- 最小的输入
- 最大的输入
我已经弄清楚了前 3 个部分,但想不出获得最小/最大数字的方法。我知道如何获得最小值/最大值的唯一方法是使用“if”语句,但不确定如何将它们合并到我的代码中。任何帮助,将不胜感激!
#include <stdio.h>
int main(int argc, const char * argv[])
{
//variables
int input;
int count = -1;
int sum = 0;
float average = 0;
do
{
printf("Enter a number.\n");
scanf("%i", &input);
count++;
sum += input;
average = sum / count;
} while (input != 0);
printf("You entered %i numbers.\n", count);
printf("The sum of your numbers are %i.\n", sum);
printf("The average of your numbers is %f.\n", average);
return 0;
}
编辑:在“do...while”循环的前面创建了一个新变量“prevnum”以等于前面的输入。使用“prevnum”变量与新输入进行比较,并使用“if...else”语句保存最小/最大值。不确定这是否是最有效或“正确”的方法,但它是功能性的并提供正确的输出。代码如下:
包括
int main(int argc, const char * argv[]) {
//variables
int input = 0;
int count = -1;
int sum = 0;
int average = 0;
int max = 0;
int min = 0;
int prevnum;
do
{
prevnum = input;
printf("Enter a number.\n");
scanf("%i", &input);
count++;
sum += input;
average = sum / count;
if(input >= prevnum && input >= max)
max = input;
else if(input < max)
max = max;
if(input <= min && input <= max)
min = input;
else if(input > min)
min = min;
} while (input != 0);
printf("You entered %i numbers.\n", count);
printf("The sum of your numbers are %i.\n", sum);
printf("The average of your numbers is %i.\n", average);
printf("The largest number entered was %i.\n", max);
printf("The smallest number entered was %i.\n", min);
return 0;
}