zoukankan      html  css  js  c++  java
  • 【每天一个编程小技巧】C++ return:使函数立即结束!

    当函数中的最后一个语句已经完成执行时,该函数终止,程序返回到调用它的模块,并继续执行该函数调用语句之后的其他语句。

    但是,也有可能强制一个函数在其最后一个语句执行前返回到被调用的位置,这可以通过return 语句完成。

    如下面程序所示,在这个程序中,函数 divide 显示了 arg1 除以 arg2 的商。但是,如果 arg2 被设置为零,则函数返回到 main 而不执行除法计算。

    #include <iostream>
    
    using namespace std;
    
    //Function prototype
    
    void divide(double arg1, double arg2);
    
    int main()
    
    {
    
        double num1, num2;
    
        cout << "Enter two numbers and I will divide the first
    ";
    
        cout << "number by the second number: ";
    
        cin >> num1 >> num2;
    
        divide(num1, num2);
    
        return 0;
    
    }
    
    void divide(double arg1, double arg2)
    
    {
    
        if (arg2 == 0.0)
    
        {
    
            cout << "Sorry, I cannot divide by zero. 
    " ;
    
            return;
    
        }
    
        cout << "The quotient is " << (arg1 / arg2) << endl;
    
    }

    程序输出结果:

    Enter two numbers and I will divide the first

    number by the second number: 12 0

    Sorry, I cannot divide by zero.

    程序中,用户输入了 12 和 0 这 2 个数字,它们被存储为变量 num1 和 num2 的双精度值。

    在第 13 行中,divide 函数被调用,将 12.0 传入 arg1 形参,并将 0.0 传入 arg2 形参。在 divide 函数中,第 19 行的 if 语句执行,因为 arg2 等于 0.0,所以第 21 行和第 22 行中的代码执行。当第 22 行中的 return 语句执行时,divide 函数立即结束,这意味着第 24 行中的 cout 语句不执行。程序继续执行 main 函数中的第 14 行。


    END!不管你是转行也好,初学也罢,进阶也可,如果你想学编程,进阶程序员~

    【值得关注】我的 编程学习交流俱乐部 !【点击进入】

    C语言入门资料(网盘链接免费分享):


     

    C语言推荐书籍(PDF免费分享):


     
  • 相关阅读:
    3里氏代换原则LSP
    2单一职责原则SRP
    1开放封闭原则OCP
    24访问者模式Visitor
    python json模块,处理json文件的读写
    python zip 绑定多个list
    python 字符串重复多次的技巧 *操作符
    python 刷新缓冲区,实时监测
    python os.getcwd 获取工作目录
    python datetime 获取时间
  • 原文地址:https://www.cnblogs.com/huya-edu/p/14893537.html
Copyright © 2011-2022 走看看