Advertisement
Guest User

stupid

a guest
Oct 22nd, 2017
343
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.87 KB | None | 0 0
  1. //This program has the user input a number n and then finds the
  2. //mean of the first n positive integers
  3.  
  4. //Christina Cho
  5.  
  6. #include <iostream>
  7. using namespace std;
  8.  
  9. int main()
  10. {
  11.     int value;       //value us some positive number n
  12.     int total = 0;      //total holds the sum of the first n positive numbers
  13.     int number;         //the amount of numbers
  14.     float mean;         //the average of the first n positive numbers
  15.    
  16.     cout<<"Please enter a positive integer"<<endl;
  17.     cin>>value;
  18.    
  19.     if(value > 0)
  20.     {
  21.         for (number = 1; number <= value; number++)
  22.              {
  23.                  total += number;
  24.              }//curly braces are optional since there is only one statement
  25.        
  26.         mean = static_cast(float)total / value;   //note the use of the typecast
  27.                                                     //operator here
  28.         cout<<"The mean average of the first "<< value
  29.         <<" positive integers is "<< mean <<endl;
  30.        
  31.        
  32.     }
  33.    
  34.     else
  35.         cout<<"Incalid input - integer must be positive" << endl;
  36.     return 0;
  37. }
  38.  
  39.  
  40. Exercise 1: Why is the typecast operator  needed to compute the mean  in the statement mean = static_cast(float)(total)/value;? What do you  thinkwill  happen if it is removed?  Modify the code  and try it. Record  what  happens. Make  sure  that you  try both even  and odd cases. Now put static_cast<float> total back  in the program.
  41. Exercise 2: What happens if you  enter  a float such  as 2.99 instead  of an integer for value? Try it and record  the results.
  42. Exercise 3: Modify the code  so that it computes the mean  of the consecutive positive integers n, n+1, n+2,  . . . , m, where the user  chooses n and m. For example, if the user  picks  3 and 9, then the program  should  find the mean  of 3, 4, 5, 6, 7, 8, and 9, which  is 6
  43.  I stuck on 2 then I couldn't move on...
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement