开发者

write a program that prompts the user to input five decimal numbers

This is the question.

write a program that prompts the user to input f开发者_Python百科ive 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?


"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;


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 <<.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜