如何在C中的main函数中使用包含scanf()的函数

use*_*219 -1 c printf scanf getter-setter

标题描述了我正在尝试做的事情,但我收到的错误消息是我从未声明过base1.我实际上知道这一点,但我不确定如何真正解决问题.

int getBase1(void);
int setBase1(double);

int main(void){
    getBase1();
    setBase1(base1);
}

int getBase1(void){
    printf("Please enter the length of a base: ");
    return;
}

int setBase1(double base1){
    scanf("%lf", &base1);
}
Run Code Online (Sandbox Code Playgroud)

Gab*_*gri 6

您必须使用指针,否则方法内的变量将不会指向相同的内存地址.使用指针,您将把值放在函数调用中传递的变量的内存地址中.还有一件事,这样你就不需要返回值了.

试试这种方式:

#include <stdio.h>
void getBase1(void);
void setBase1(double *base1);

int main(void){
    double base1;
    getBase1();
    setBase1(&base1);
    printf("%lf", base1);
}

void getBase1(void){
    printf("Please enter the length of a base: ");
}

void setBase1(double *base1){
    scanf("%lf", base1);
}
Run Code Online (Sandbox Code Playgroud)

  • @LathalProgrammer--"main()"是一个特例.这里不需要明确的`return`语句(因为C99); 在这种情况下,如果在没有显式"return"的情况下到达`main()`的结尾,则返回值0. (2认同)