2011-02-15 51 views
-1

我的挑战是编写一个程序,将用户的GPA作为浮点值存储在数组中。用户最多可以输入30个GPA,并在每个输入值输入后显示平均值。我感到困惑的是如何在循环中使用scanf()函数来将浮点值存储在数组中。任何人都可以用示例代码解释吗?如何分配用户输入以存储到数组

好吧,这是我已经开始的代码。我知道这是假的,但我希望每个人都能更好地了解我正在编写的程序。我希望用户输入他们有多少GPA。他们输入的数字将是我将拥有的数组数量。

#include <stdio.h> 
main() 
{ 
    int loopcount = 0; 
    int NumGpa = 0; 
    NumGpa = 0 - 1; 
    float = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25; 
    int gpa[NumGpa] ={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25}; 
    int i = 0; 
    int total =0; 

    printf("\t\tWelcome to the GPA calculator.\n "); 
    printf("Please enter the number of classes you have counted for you GPA: "); 
    scanf("%d", &NumGpa); 

    while (loopcount &lt; NumGpa) 
    { 
     printf("\nenter your first GPA: "); 
     scanf("%d", &1); //??????????????(i want loops to use scanf() if order &2,&3 ect? 

     for (i=0; i&lt;gpa; i++) 
     { 
      total += arbin[NumGpa]; 
     } 

     printf(" you average gpa is %d", NumGpa/????); 
     getchar(); 
    } 
} 
+0

OK所以这是代码,我已经开始我知道它BOGUS但希望每个人都获得程序IM试图写一个更好的想法。我希望用户输入多少GPA的信息。他们输入的数字将是我将拥有的阵列数量。 – Arbin 2011-02-15 05:35:52

+4

如果您关闭大写锁定键,则可以减少虚假。保证让你成为更好的程序员。 – 2011-02-15 06:40:09

回答

0

scanf("%f",&arrayVariableName[i]);

+0

小错字 - 你想'&arrayVariableName`。 – 2011-02-15 04:32:23

0

当您阅读与scanf一个float,您传递有关float的地址。您可以使用address-of运算符(&),以与其他任何方式相同的方式获取数组中项目的地址。

或者,您可以简化一些事情。在C中,下标运算符([])等同于指针操作。特别是,a[b]相当于*(a+b)。然而,&*几乎是完全相反的,所以在这种情况下,他们最终会取消彼此。因此,如果您愿意,您可以使用a+b,其中一个是数组的名称,另一个是您想要读取的数组中项目的索引。

0
int i = 0; // current user 
float user_gpa[NUM_USERS]; // your array 

while (i < num_users) { 
    scanf("%f", &user_gpa[i]); // reading data for the i-th user (%f means float) 
    i = i + 1; // next user 
} 
0

试试这个

for(i=0; i<30; i++) 
scanf("%f", arrayname[i]); 

如果你想直接平均再试试这个

float temp, ave=0; 
int i; 
for (i=1; i<=30; i++) 
{ 
scanf("%f", &temp); 
ave += temp; 
} 
printf("%f", ave/30); 
0

喏,你的代码少了不少错误,或许这可能帮助。

enter code here 

void main()(
    int loopcount = 0; 
    int NumGpa; 
    NumGpa = 0 - 1; 
/* 
    float = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25; i don't understand why were you doing this. 
    int gpa[NumGpa] ={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25}; 
*/ 
    int i = 0; 
    float total =0; /this is float so that output will be accurate. 
    printf("\t\tWelcome to the GPA calculator.\n"); 
    printf("Please enter the number of classes you have counted for you GPA: "); 
    scanf("%d", &NumGpa); 
    int gpa[NumGpa]; 
    while (loopcount < NumGpa) 
    { 
     printf("\nenter your %d GPA: ", loopcount); 
     scanf("%d", &gpa[loopcount]); 
     loopcount++; 
    } 
    for (i=0; i<NumGpa; i++) 
    { 
     total += gpa[i]; 
    }  
     printf(" you average gpa is %f", total/NumGpa); 
     getchar(); 
}