1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

A code for caculate 1+2+3+...+n

Discussion in 'C++' started by wdliming, Oct 7, 2010.

  1. wdliming

    wdliming New Member

    A code for caculate 1+2+3+...+n
    Code:
    #include <iostream>
    using namespace std;
    int main()
    {
     int i=0;
     int temp=0;
     int n;
     while (1)//use this "while(1)", i can caculate all the time;
     {
      /*input a number n,ready for calculate the: 1+2+....+n*/
      cout<<"input a number n:"<<endl;
      cin>>n;
      for(i = 0; i <= n; i++)
      {
       temp=temp+i;
       //i++;
      }
      cout << "The value = "<< temp <<endl<<endl;
      temp = 0;//clare temp, in order to recaculate.
     }
        cout << "Hello world!" << endl;
        return 0;
    }
    
    welcome to give some advices!!
     
  2. xpi0t0s

    xpi0t0s Mentor

    Always practice good indentation.

    Don't call variables that have significant meaning in the program throwaway names like "temp".

    The calculation starts at 1 so start the loop at 1. Doesn't matter too much in this case but when you do something more interesting than adding the loop variable to an accumulator the zero might have more effect.

    Lern tu spel. Who's Clare?

    Don't use cin to read input from the user. It gets confused too easily. Use fgets to read a whole line of input, make sure you check you got the lot, then decode what they entered; this is MUCH more secure.

    No graceful exit possible; the user has to kill the process when he's done. Two prompts could be tedious, so maybe ask "input a number or zero to exit", then process the zero entry as an exit request.

    No error handling. What happens when temp exceeds MAXINT cos they enter a silly number?


    Not bad for starters. Suggestion for your next project: modify it so that it can handle numbers greater than MAXINT (which is compiler dependent, but could be 2^32-1), decide on a new upper limit, and throw an error when the user enters a number that's too large. Extra points if you don't just use 64-bit integers.
     
    wdliming likes this.
  3. jimblumberg

    jimblumberg New Member

    I must respectively disagree with the use of fgets in C++ code, because it does not understand C++ std::string. In my view this fosters the continued use of C style character strings over the use of std::string. In C++ if you don't like cin I would suggest the use of getline(cin, std::string). Then use stringstream to convert to your desired type.

    I believe that in C++ you should prefer std::string over Cstring, std::vector over c arrays.


    Jim.
     
  4. xpi0t0s

    xpi0t0s Mentor

    No problem, we all work different ways. I'll switch from char arrays once C++ has a decent way of doing string formatting that's as concise as the %-notation, currently the only option seems to be really clunky: ostringstream var; var<<format<<var1<<format<<var2<<format<<var3 - yuck! Give me %s%02d%I64d any day over that lot. Mind you, I know all the printf stuff, and I've never found anywhere that adequately documents all the std::string formatting stuff, so if you have a reference for it I'd probably be up for it.
     
  5. jimblumberg

    jimblumberg New Member

    You might be interested in the Boost Format library. boost/format

    Jim
     
  6. wdliming

    wdliming New Member

    I will continue~~ to modify my code..thank you, i am a freshman for c++,and i am looking at The C++ Programming Language now, it is a good,classic book.
    Thank you!!
     
  7. wdliming

    wdliming New Member

    i have made some promotion ,haha....
    Code:
    #include <iostream>
    
    using namespace std;
    
    int cope()
    {
        int i=0;
    	int temp=0;
    	int n;
        cout <<"Input a number n:"<<endl;
        cin >> n;/*input a number n,ready for calculate the: 1+2+....+n*/
        if(n > 65536)
        {
            cout << "Error! The number you input is too big!~~Try again:" << endl << endl;
            //cin >> n;
            //break;
        }
        else if(n>=0 && n <= 65536)
        {
            for(i = 0; i <= n; i++)
            {
                temp=temp + i;
                //i++;
            }
            cout << "The value = "<< temp <<endl<<endl;
            temp = 0;//clare temp, in order to recaculate.
        }
        return 0;
    }
    
    int main()
    {
    				//calculate the: 1+2+....+n
        cout << "Hello!~" <<endl;
        cout << "This is the program for the 1+2+....+n "<< endl;
    
    	while (1)//use this "while(1)", i can caculate all the time;
    	{
            cope();
    	}
    
        return 0;
    }
     
    Last edited by a moderator: Oct 15, 2010

Share This Page