编写一个程序,提示用户输入五个十进制数字

时间:2010-04-08 21:33:36

标签: c++

这就是问题。

编写一个程序,提示用户输入五位十进制数。然后程序应该添加五个十进制数,将总和转换为最接近的整数,m并打印结果。

这是我到目前为止所得到的:

// 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;
}

现在我只需要将总和(f)转换为最接近的整数m并打印结果。我该怎么做?

3 个答案:

答案 0 :(得分:1)

  

“声明m”意味着说

int m;

如果你说

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

这里甚至不需要施法:

m=f; //works just as well

现在你可以打印m

cout<<m;

答案 1 :(得分:0)

你需要

  1. 声明m。声明如下: double a, b , c , d , e, f;
  2. 调用舍入功能或更改使用=时发生的默认舍入。
    • 默认情况下,将double值分配给int变量会向下舍入。您可以使用fesetround( FE_TONEAREST );
    • 中的#include <fenv.h>更改默认值
    • 或者,您可以从round
    • 调用函数#include <cmath>
    • 这些功能目前都不是严格的标准C ++;它们是标准C,并计划成为标准C ++。
  3. 使用mcout添加要打印<<的语句。

答案 2 :(得分:0)

这就是答案:

// 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;
}

通过从double到integer的类型转换,在添加.5之后将截断小数。这意味着如果你有一个像13.4这样的数字并且你向它添加.5然后截断小数它将向下舍入。如果您有13.6并添加.5然后截断小数,则它将是14.这就是您使用类型转换向上和向下舍入的方式。

相关问题