如何在C主函数中使用包含scanf()的函数 [英] How to use a function containing scanf() in the main function in C

查看:107
本文介绍了如何在C主函数中使用包含scanf()的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题说明了我要执行的操作,但是我收到了从未声明base1的错误消息.我确实知道这一点,但是我不确定如何真正解决问题.

The title describes what I'm trying to do, but I'm getting the error message that I never declared base1. I actually know this, but I'm not exactly sure how to actually fix the problem.

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);
}

推荐答案

必须使用指针,否则方法内的变量将不会指向相同的内存地址.使用指针,您可以将值放入函数调用中传递的变量的内存地址中. 还有一件事,通过这种方式,您将不需要返回值.

You must use pointer, otherwise the variable inside the method will not point to the same memory adress. Using pointer you'll be putting the value inside the memory address of the variable that you pass in the function call. One more thing, this way you will not need return values.

尝试这种方式:

#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);
}

这篇关于如何在C主函数中使用包含scanf()的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆