tags:

views:

367

answers:

2

This is the question.

write a program that prompts the user to input five decimal numbers. the program should then add the five decimal numbers, convert the sum to the nearest integer,m and print the result.

This is what I've gotten so far:

// p111n9.cpp : Defines the entry point for the console application.
//

#include <iostream>
using namespace std;

double a, b , c , d , e, f;

int main(int argc, char* argv[])
{
 cout << "enter 5 decimals: " << endl;
 cin >> a >> b >> c >> d >> e;
 f = a + b + c + d + e;
 return 0;
}

Now I just need to convert the sum(f) to the nearest integer, m and print the result. How do I do this?

A: 

You need to

  1. Declare m. A declaration looks like this: double a, b , c , d , e, f;
  2. Call a rounding function or change the default rounding that occurs when you use =.
    • Assigning a double value to an int variable rounds down by default. You can change the default with fesetround( FE_TONEAREST ); from #include <fenv.h>.
    • Alternately you can call the function round from #include <cmath>.
    • Neither of these functions are currently strictly standard C++; they are standard C and are scheduled to become standard C++.
  3. Add a statement to print m, using cout and <<.
Potatoswatter
thank you for the reply but i am totally newbie at this computer science... i cant understand :(
SkyBoxer
@user: are you taking a class or teaching yourself? You should refer to class notes instead of Stack Overflow if you have them.
Potatoswatter
doing myself...
SkyBoxer
Do you have a book?
GMan
+1  A: 

"declare m" means say

int m;

if you say

m = (int)f; // it means the int value of f is assigned to m.

The casting is actually not even necessary here:

m=f; //works just as well

now you can print m

cout<<m;
Stef
This truncates (aka, rounds down). round(f) from #include<cmath> is better, but your solution does provide an insight into how one might go about implementing a rounding function.
Niki Yoshiuchi