How to start from beginning of the program

前端 未结 6 1777
灰色年华
灰色年华 2021-01-17 02:00

I am a very beginner in c++. i am just learning abc of this language.. i created this small program that would add:

#include 
   using namesp         


        
6条回答
  •  死守一世寂寞
    2021-01-17 02:11

    Since you are starting, I am going to suggest changing your code a little bit:

    #include 
    using namespace std;
    
    float add(float a, float b)
    {
        return a+b;  
    }
    
    // Function that does the core work.
    void read_input_print_sum()
    {
       float num1;
       float num2;    
    
       cout<<"add...enter digits \n";
       cout<<"first digit: ";
       cin>>num1;
       cout<<"\n Second number: ";
       cin>>num2;
    
       cout<< "your sum is: "<

    Now, you can add various methods to call the core function repeatedly. One has been suggested in the answer by Rakibul Hassan.

    That can be implemented with:

    int main()
    {
       while (true)
       {
         read_input_print_sum();
       }
       system("pause");    
    }
    

    Another way: Ask the use whether they want do the work again.

    bool getRepeat()
    {
      cout << "Do you want to repeat? (Y/N): ";
      int yesno = cin.getc();
      return ( yesno == 'Y' || yesno == 'y' );
    }
    
    int main()
    {
       bool repeat = true;
       while (repeat)
       {
         read_input_print_sum();
         repeat = getRepeat();
       }
       system("pause");    
    }
    

    Another way: Ask the number of times they wish to repeat the computation before you start.

    int main()
    {
       int N = 0;
       cout << "How may times do you want to add numbers: ";
       cin >> N;
    
       for ( int i = 0; i <= N; ++i )
       {
         read_input_print_sum();
       }
       system("pause");    
    }
    

提交回复
热议问题