我想要使用的主要代码写出来。我需要做的就是让用户输入五个数字。然后,一旦他们插入数字,我需要将它们输入到数组中,以便可以计算它们。我试图了解如何成功获取用户输入并使用它,但一直无法弄明白。
int
main (int argc, char **argv)
{
int number1;
int number2;
int number3;
int number4;
int number5;
int a[5];
printf("Enter a number\n");
scanf ("%d, number1");
printf("Enter a number\n");
scanf ("%d, number2");
printf("Enter a number\n");
scanf ("%d, number3");
printf("Enter a number\n");
scanf ("%d, number4");
printf("Enter a number\n");
scanf ("%d, number5");
a[0] = number1;
a[1] = number2;
a[2] = number3;
a[3] = number4;
a[4] = number5;
int mean = (a[0] + a[1] + a[2] + a[3] + a[4]) / 5;
int difference0 = a[0] - mean;
int difference1 = a[1] - mean;
int difference2 = a[2] - mean;
int difference3 = a[3] - mean;
int difference4 = a[4] - mean;
int variance = ((difference0 * difference0) + (difference1 * difference1) + (difference2 * difference2) + (difference3 * difference3) + (difference4 * difference4)) / 5;
double sdeviation = sqrt(variance);
printf("the mean of the array is %d\n",mean);
printf("the variance of the array is %d\n",variance);
printf("the standard deviation of the array is %f\n",sdeviation);
return 0;
}
答案 0 :(得分:2)
首先,您不需要numberN
局部变量。您可以定义数组并直接读取数字。
那就是说,不要一遍又一遍地重复相同的代码。
更改代码
#define ARRSIZE 5
int a[ARRSIZE] = {0};
for (int i = 0; i < ARRSIZE ; i++) {
printf("Enter a number\n");
scanf ("%d", &a[i]);
}
此外,检查scanf()
函数的返回值以确保扫描成功是一种很好的做法。
建议:始终启用编译器警告并尝试解决警告。
答案 1 :(得分:0)
只是为了添加@Sourav的其他答案,你必须学习作为程序员的原则。其中之一是,如果你必须重复任何微小变化的任务,你很可能会使用一个循环。另外,引用Sinan Ünür
当您发现自己在变量名称中添加整数后缀时,请认为我应该使用数组。
如果你想创建5个int
个变量而你只是命名每个变量:number1 ... number 5,那么你应该创建一个数组来保存所有变量。它更容易,并且您可以动态地引用每个动作,因为数组的工作方式。
int numbers[5]; //Now you can refer to each one by numbers[X]
...
for (int i = 0; i < 5; ++i) {
numbers[i] = a[i] - mean;
}
这些只是我将添加到您的代码中的两个非常小的修改,以便它在眼睛上更小更容易。随着你的进展,你会更好地学习这一点。
答案 2 :(得分:0)
在要分配即将发生的值的变量之前,您需要&amp; 运算符。在这种情况下,您说的是 num1 = 4 ,其中for是用户的值。
试试这个:
#include <stdio.h>
#include <math.h>
int main()
{
int num1,num2, num3, num4, num5;
printf("Enter #1:\n");
scanf ("%d", &num1);
printf("Enter #2:\n");
scanf ("%d", &num2);
printf("Enter #3:\n");
scanf ("%d", &num3);
printf("Enter #4:\n");
scanf ("%d", &num4);
printf("Enter #5:\n");
scanf ("%d", &num5);
int mean = (num1 + num2 + num3 + num4 + num5) / 5;
int difference0 = num1 - mean;
int difference1 = num2 - mean;
int difference2 = num3 - mean;
int difference3 = num4 - mean;
int difference4 = num5 - mean;
int variance = ((difference0 * difference0) + (difference1 * difference1) + (difference2 * difference2) + (difference3 * difference3) + (difference4 * difference4)) / 5;
double sdeviation = sqrt(variance);
printf("the mean of the array is %d\n",mean);
printf("the variance of the array is %d\n",variance);
printf("the standard deviation of the array is %f\n",sdeviation);
return(0);
}