“variable” was not declared on this scope [C]

2019-09-27 10:09发布

I have these 3 errors when compiling main:

[Error]"media" was not declared on this scope

[Error]"max" was not declared on this scope

[Error]"min" was not declared on this scope

[Error]"calc" was not declared on this scope

Do I need to scan inside the main and then use the function?

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

typedef struct{
    char name[50];
    float medias;
}DATA;

DATA *p;


float calc(DATA *p,float media, float max, float min)
{
    int a;
    max=0;
    min=20;
    float soma=0; 
    for(a=0; a<3; a++)
    {
        printf("\nWrite the score of your %dº test: ", a+1);
        scanf("%f", p->medias);
        if (p->medias>max){
            max=p->medias;
        }
        if (p->medias<min){
            min=p->medias;
        }
        soma=soma+p->medias;
    }
    media=soma/3;
    return p, media, max, min;
}

int main()
{
    calc(p, media, max, min);
    system("cls");
    printf("Higher score: %f \nLowest score: %f \nMedia: %f", max, min, media);
    getch();
}

标签: c
2条回答
趁早两清
2楼-- · 2019-09-27 10:51

There are problems in your code

1) You are returning a float in function definition but returning four values there.If you need to return multiple values store return values in an global array or reference to some local array and fill in it or make the return value as void just change the values inside the calc function described in step(2)

2) If you want calc function to store the values in min, max and media you will have to declare in the main like float min, max, media; in the first line of main and pass the values as pointers so calc should be modified to calc(DATA *p,float* media, float* max, float* min) and it should be used in main as calc(p, &media, &max, &min ) and inside the calc you should have statements like *max=0; instead of max=0;

3) soma variable is storing p->medias 3 times and dividing it by 3. so at the end it will store p->medias. So no need to calculate it just assign it the value.

查看更多
Evening l夕情丶
3楼-- · 2019-09-27 11:07

You have't declared variables media, max, min. They either need to be local in main, or global. In general it is a good idea to have them as local in main, including p which you have put as global but then pass as parameter.

In your program, media, max, and min are parameters in calc. As they are, those variables can only be used inside calc.

Do I need to scan inside the main and then use the function?

If you mean scanf() to read the values from keyboard input, probably yes. It really depends on what you need.

However, while you surely need to declare the variables first, you are also overwriting the value of the parameters inside calc, ignoring whatever values are passed to the function.

float calc(DATA *p,float media, float max, float min)
{
    int a;
    max=0;
    min=20;
查看更多
登录 后发表回答