Reputation: 103
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?
Upvotes: 2
Views: 19567
Reputation: 1
This is the answer:
// 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;
cout << static_cast<int> (f + .5)<< endl;
return 0;
}
By type casting from double to integer the decimal is being truncated AFTER the .5 is added. This means if you have a number like 13.4 and you add .5 to it and then truncate the decimal it will round down. If you have 13.6 and add .5 and then truncate the decimal it will be 14. That is how you round up and down with type casting.
Upvotes: 0
Reputation: 446
"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;
Upvotes: 1
Reputation: 137780
You need to
m
. A declaration looks like this:
double a, b , c , d , e, f;
=
.
double
value to an int
variable rounds down by default. You can change the default with fesetround( FE_TONEAREST );
from #include <fenv.h>
.round
from #include <cmath>
.m
, using cout
and <<
.Upvotes: 0