C++ return:使函数立即结束
发布时间:2020-12-16 07:38:40 所属栏目:百科 来源:网络整理
导读:当函数中的最后一个语句已经完成执行时,该函数终止,程序返回到调用它的模块,并继续执行该函数调用语句之后的其他语句。但是,也有可能强制一个函数在其最后一个语句执行前返回到被调用的位置,这可以通过? 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 firstn"; 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. n" ; return; } cout << "The quotient is " << (arg1 / arg2) << endl; }程序输出结果:
Enter two numbers and I will divide the first (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |