简体   繁体   English

在C中输入的结构和值

[英]struct and values entered in C

I have a program that does not work. 我的程序无法正常工作。 The problem for example is: 例如,问题是:

You input 2 for students, then enter mark 5 for the first student and then 10 for second student. 您为学生输入2,然后为第一个学生输入标记5,然后为第二个学生输入标记10。

The output sum in the fun() function should return 15 . fun()函数中的输出和应返回15。 But instead, it returns 20. 但是,它返回20。

This is my code so far: 到目前为止,这是我的代码:

struct mark{
   int x;   
};

int main(){
    int n;
    printf("Enter the number of student: ");
    scanf("%d",&n);

    struct mark *marks= malloc(n * sizeof(struct mark)); ;

    for (int i = 0; i < n; i++ ){
        printf("Enter mark: ");
        scanf("%d",&(*marks).x);
    }

   fun(marks,n);

    free(marks);
    return 0;
}

void fun(struct mark *marks, int n){
    int sum =0,i;
    for (i = 0; i < n; i++ ){
        sum= sum+(*marks).x;

    }
    printf("Sum: %d \n",sum);

}
    scanf("%d",&(*marks).x);

Means you are reading into the first mark in marks . 意味着你正在阅读到的第一markmarks

You already have a for loop and a counter variable for reading into it, so use it. 您已经有一个for循环和一个用于读取它的计数器变量,因此请使用它。 change 更改

sum= sum+(*marks).x;

to

sum= sum+marks[i].x;

which is also equivalent to 这也等同于

sum = sum+(*marks+i).x;

Do the same for 为...做同样的事情

scanf("%d",&(*marks).x);

change it to 更改为

scanf("%d",&marks[i].x);

again, 再次,

marks[i].x is equivalent to (*marks+i).x marks[i].x等效于(*marks+i).x

The point is that you want to access the second mark in marks in your second iteration of your for loop. 问题的关键是,你要访问的第二个markmarks在你的for循环的第二次迭代。 Also, don't forget to free() your marks when your program is done. 同样,程序完成后,请不要忘记free()您的marks

change : 变化:

scanf("%d",&marks[i].x);

and: 和:

sum= sum+marks[i].x;

Inside main in this piece of code: 在这段代码的main内部:

 for (int i = 0; i < n; i++ ){
        printf("Enter mark: ");
        scanf("%d",&(*marks).x);
    }

You are always assigning mark to 1st array element. 您总是将标记分配给第一个数组元素。

Inside fun in this piece of code: 这段代码的内在fun

for (i = 0; i < n; i++ ){
        sum= sum+(*marks).x;
    }

you are not iterating over the marks array, but instead always reading 1st array value. 您没有遍历标记数组,而是始终读取第一个数组的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM