Advertisement

《Essential C++》笔记之return;分析

阅读量:

《Essential C++》笔记之return;分析

举例分析:

在本例中,被调用的辅助函数 bool fibonElem(int, int&) 返回布尔值 true 或 false,并将这些结果传递给主程序进行处理。

复制代码
    //小问学编程
    #include <iostream>
    using namespace std;
    
    bool fibon_elem(int,int&);
    
    int main()
    {
    int pos;
    cout<<"请输入Fibonaccei数列中某个元素的位置:"<<' ';
    cin>>pos;
    
    int elem;
    if(fibon_elem(pos,elem))
        cout<<"位置为"<<' '<<pos<<' '
            <<"的元素是:"<<elem<<endl;
    else cout <<"Sorry.Could not calculate element#"
              <<pos<<endl;
    }
    
    bool fibon_elem( int pos, int& elem )
    {
    
    	if ( pos <= 0 || pos > 1024 )
    	{
    		 cerr << "invalid position: " << pos
    			  << " -- cannot handle request!\n";
    
         elem = 0;
         return false;
    	}
    
    elem = 1;
    int n_2 = 1, n_1 = 1;
    for ( int ix = 3; ix <= pos; ++ix )
    {
    		 elem = n_2 + n_1;
    		 n_2 = n_1; n_1 = elem;
    }
    
    return true;
    }
    //本代码改自《Essential C++》侯捷译P38~P39
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
    AI助手

运行结果:

在这里插入图片描述

什么时候用 return;
(不是return 0;是return;)

当函数返回类型设置为void时(即无需返回任何值), 采用return语句可提前终止子函数的执行流程;然而, 当子函数完成返回到主函数时, 其返回的位置将不影响主函数后续执行的代码块。

例:

复制代码
    //小问学编程
    #include <iostream>
    using namespace std;
    
    void fibon_elem(int,int&);
    
    int main()
    {
    int pos;
    cout<<"请输入Fibonaccei数列中某个元素的位置:"<<' ';
    cin>>pos;
    
    int elem;
    fibon_elem(pos,elem);
    cout<<"虽然子函数遇到return;提前结束,但主函数还将继续,故本行会被打印";
    }
    
    void fibon_elem( int pos, int& elem )
    {
    
    	if ( pos <= 0 || pos > 1024 )
    	{
    		 cerr << "invalid position: " << pos
    			  << " -- cannot handle request!\n";
    
         elem = 0;
         return;
    	}
    
    elem = 1;
    int n_2 = 1, n_1 = 1;
    for ( int ix = 3; ix <= pos; ++ix )
    {
    		 elem = n_2 + n_1;
    		 n_2 = n_1; n_1 = elem;
    }
    if(elem)
        cout<<"位置为"<<' '<<pos<<' '
            <<"的元素是:"<<elem<<endl;
    else cout <<"Sorry.Could not calculate element#"
              <<pos<<endl;
    return;
    cout<<"由于子函数遇到return;提前结束,故本行将不会被打印";
    }
    //本代码改自《Essential C++》侯捷译P38~P39
    
    
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
    AI助手

运行结果:

在这里插入图片描述

全部评论 (0)

还没有任何评论哟~