我们可以使用return语句从用户定义的函数返回值吗? [英] Can we use return statement to return value from a user defined function?

查看:81
本文介绍了我们可以使用return语句从用户定义的函数返回值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个阶乘程序中输入任何非数字或负数时,程序应该要求输入值,但在输出中程序将被终止。



是因为我在display()函数中返回-1?如果是这样的话,如果函数是要返回一个值,那么是否必须将一个变量(或其他函数)值返回给函数?



请指导我怎么做利用return语句检查一个值而不退出程序



我尝试过:



In this factorial program when entered any non numeric or negative number then the program should ask to renter the value but in the output the program is getting terminated.

Is it because I am returning -1 in display() function? If so then is it compulsory to return a variable(or other function) value to a function if the function is meant to return a value?

Kindly guide me how do make use of return statement to check for a value without exiting the program

What I have tried:

#include <stdio.h>

int display();
void fact_fun(int num_fact);

int main()
{
    int num = 0;
    char next;

    next=display();
    
    if(next==-1) //WHEN ANY CHARACTER OR NEGATIVE NUMBER IS ENTERED IT WILL ASK TO RENTER
    {
        printf("\nOnly positive number is allowed");
        display();
    }

    while(next>=0) //WHEN NEGATIVE NUMBER IS ENTERED IT WILL END THE LOOP
 {
    num = next;
    fact_fun(num);
    next=display();
 }
    return 0;
}

int display()
{
    char inp[10]={0};
    int  input;
    int index=0;
    printf("\nEnter number to find factorial or press ENTER KEY to exit : ");

    while(((input=getchar())!=EOF)&(index<10))
    {
        if((input>='0')&&(input<='9'))
        {
            inp[index++]=input;
        }
        else if(input=='\n')
            break;
        else
            return -1;
    }
    input=atoi(inp);

    return input;
}

void fact_fun(int num_fact)
{
int fact =1;
    if(num_fact == 0)
    {
        printf("\nFactorial of %d is 1",num_fact);
        return;
    }
    else
    {
        for(int i = 1; i<= num_fact; i++)
        {
            fact = fact*i;
        }
        printf("\nFactorial of %d is %d",num_fact,fact);
    }
}

推荐答案

printf("\nOnly positive number is allowed");
display();



您没有捕获显示功能返回的值。

您应该循环获取有效数字,类似于:


You are not capturing the value returned from your display function.
You should us a loop to get a valid number, something like:

do
{
    printf("\nEnter number to find factorial or press ENTER KEY to exit : ");
    next = display()
    if (next == 0)
        return;
    if (next == -1)
    {
        printf("\nOnly positive number is allowed");
        continue;
    }
    fact_fun(next);
} while (1);


这篇关于我们可以使用return语句从用户定义的函数返回值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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