如何在一个void函数中进行扫描,并在主函数中显示结果,以便在C中的另一个void中使用



void本身工作得很好,但是我如何将变量从一个void调用到另一个void呢?我遇到的问题是enter_user_name(void)中的名称没有被放入enter_user_exam(void)

的打印中。
#include <stdio.h>
#include <ctype.h>
#include <string.h>
void enter_user_name(void);
void enter_user_exam(void);
int main()
{
    enter_user_name();
    enter_user_exam();
    return 0;
}
// Define the function:
// Note: No semicolon after function name
void enter_user_name()
{
    /* Need next two lines for printf() operation */
    setvbuf(stdout, 0, _IONBF, 0);
    setvbuf(stdin, 0, _IONBF, 0);
    char guyname[32]= {0};
    char lastname[32]= {0};
    printf("Enter your first and last name : ");
    scanf("%s %s", &guyname, &lastname);
    guyname[0] = toupper( guyname[0] );
    int len = strlen(guyname);
    for(int i=1; i<len ; i++)
    {
        guyname[i] = tolower( guyname[i]);
    }
    lastname[0] = toupper( lastname[0] );
    int len1 = strlen(lastname);
    for(int k=1; k<len1; k++)
    {
        lastname[k]= tolower( lastname[k]);
    }
    printf("Your name is %s %sn", guyname, lastname);
}
void enter_user_exam(void)
{
    /* Need next two lines for printf() operation */
    setvbuf(stdout, 0, _IONBF, 0);
    setvbuf(stdin, 0, _IONBF, 0);
    int option = 0;
    int sum = 0;
    char guyname[32]= {0};
    char lastname[32]= {0};
    int maxscore = 100;
    int scores[3] = {0};
    float average = ((float)sum/(maxscore*3)) * 100;
    for( int i=0; i<3; i++)
    {
        printf("Assuming the max score is 100, what was your score for exam %i?n",i+1);
        scanf("%i",&scores [i]);
        while(scores [i]>maxscore)
        {
            printf("Your score should not be higher than max score.n");
            printf("What was your score for exam %i?n",i+1 );
            scanf("%i",&scores [i]);
        }
    }
    for(int i=0; i<3; i++)
    {
        sum += scores[i];
    }
    average = ((float)sum/(maxscore*3)) * 100;
    printf("%s %s, the exam scores you input are %i ,%i ,and %inn",guyname,lastname, scores[0], scores[1], scores[2]);
}

从函数中获取数据有三种方法:

  1. 函数返回数据
  2. 函数获取指向数据的指针作为参数,并将其填入
  3. 数据存储在全局变量
在我看来,上面的列表是按优先顺序排列的。最好的解决方案通常是返回数据(尽管您必须小心不要返回指向局部变量的指针),而最糟糕的是使用全局变量。

相关内容

  • 没有找到相关文章

最新更新