函数中的嵌套函数或调用函数

时间:2017-02-16 00:30:07

标签: c function nested

所以,我不确定如何开始,所以我将从一些代码开始:

    int main()
{
    system("cls");
    printf( "1. D4\n" );
    printf( "2. D6\n" );
    printf( "3. D8\n" );
    printf( "4. Exit\n" );
    printf( "Selection: " );
    scanf( "%d", &input );
    switch ( input ) {
        case 1:            
            roll_d4();
            break;

首先,我有这个,当我选择一个选择时,它可以让我获得我想要的功能。所以当我进入D4功能时,我有这个:

void roll_d4() {
system("cls");
printf("How many D4 do you want to roll?\n");
printf("Enter a number 1-20");
printf("\nSelection: ");
scanf("%d", &input);
switch (input){
    case 5:
    exit(0);
    d4_number();
}

现在,每次我尝试运行它时,它都不喜欢d4_number();,并说它是一个隐含的声明。我只是试图让你选择一个选择并让它转到代码的下一部分,在这种情况下,一个函数将实际滚动一个骰子而不是像这样的菜单。但这样做是不行的,我不知道该做什么。

编辑:代码添加。这是完整的程序:

#include <stdio.h>
#include <ctype.h>
#include <time.h>
#include <stdlib.h>
#include <stdbool.h>
#include<string.h>
#include<process.h>
#include<conio.h>
#include<ctype.h>
char response;
    int sum = 0;
    time_t t;
    int result;

    int die_d4_1 = 0;
    int die_d4_2 = 0;
    int die_d4_3 = 0;
    int die_d4_4 = 0;
    int die_d4_5 = 0;
    int input;

void roll_d4() {
    system("cls");
    printf("How many D4 do you want to roll?\n");
    printf("Enter a number 1-20");
    printf("\nSelection: ");
    scanf("%d", &input);
    switch (input){
        case 5:
        exit(0);
        d4_number(0);
    }
}
void roll_d6()
{
    printf( "How many D6 do you want to roll?" );
}
void roll_d8()
{
    printf( "How many D8 do you want to roll?" );
}

void d4_number(){
    printf("How many d4 do you want to roll?");
}

int main()
{
    system("cls");
    printf( "1. D4\n" );
    printf( "2. D6\n" );
    printf( "3. D8\n" );
    printf( "4. Exit\n" );
    printf( "Selection: " );
    scanf( "%d", &input );
    switch ( input ) {
        case 1:            /* Note the colon, not a semicolon */
            roll_d4();
            break;
        case 2:          
            roll_d6();
            break;
        case 3:         
            roll_d8();
            break;
        case 4:        
            printf( "Thanks for playing!\n" );
            break;
        default:            
            printf( "Bad input, quitting!\n" );
            break;
    }
    getchar();

}

它显然非常不完整,但我只是在添加更多内容之前尝试解决此问题。

3 个答案:

答案 0 :(得分:2)

你需要在调用之前给d4_number()一个原型,所以编译器知道它需要什么参数以及它返回什么。 否则它仍然链接(由于历史原因)并假设它返回一个int。

答案 1 :(得分:1)

如果你仔细看看这段代码

switch (input){
    case 5:
    exit(0);
    d4_number(0);
}

您可以注意到在d4_number函数之前调用了exit函数。在这种情况下,d4_number函数永远不会执行,因为整个程序停止并以0作为返回码退出。

其他问题是d4_number函数定义不接受任何参数,但在语句d4_number(0)中传递了一个额外的参数。

答案 2 :(得分:0)

好吧,我觉得自己像个白痴。我所要做的只是移动声明:

        void d4_number(){
    printf("How many d4 do you want to roll?");
}

上面

void roll_d4() {
system("cls");
printf("How many D4 do you want to roll?\n");
printf("Enter a number 1-20");
printf("\nSelection: ");
scanf("%d", &input);
switch (input){
    case 5:
    d4_number(0);
}

所以在打电话之前就宣布了......我觉得这真的很蠢,但感谢大家的快速反应!

相关问题