Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C:我怎样才能使一个数字总是四舍五入_C_Function_Rounding - Fatal编程技术网

C:我怎样才能使一个数字总是四舍五入

C:我怎样才能使一个数字总是四舍五入,c,function,rounding,C,Function,Rounding,我想做一个基于时间计算成本的函数。对于任何少于三小时的时间,它都将返回2美元的统一费率。每超过一小时或不足一小时,它将额外收取0.50美元。小时由用户作为浮点数据类型输入,精确到小数点后2位。我怎样才能把时间缩短到一个小时呢?以下是迄今为止我为该函数编写的代码: int calculateCharges(float hours) { if (hours <= 3){ return 2.00 } else int计算费用(浮动小时) { 如果(hours首先,您使用的数据类型in

我想做一个基于时间计算成本的函数。对于任何少于三小时的时间,它都将返回2美元的统一费率。每超过一小时或不足一小时,它将额外收取0.50美元。小时由用户作为浮点数据类型输入,精确到小数点后2位。我怎样才能把时间缩短到一个小时呢?以下是迄今为止我为该函数编写的代码:

int calculateCharges(float hours)
{
 if (hours <= 3){
    return 2.00
}
else
int计算费用(浮动小时)
{

如果(hours首先,您使用的数据类型
int
,它不能保存小数(甚至在调用函数之前,它会隐式地将它们四舍五入为零)。您应该使用
双精度
,因为这是小数的正确数据类型

您还需要使用函数,该函数给出大于或等于
x
的最近整数

#include <math.h>

double calculateCharges(double hours)
{
  if (hours <= 3) {
    return 2.00;
  } else {
    // return $2.00 for the first 3 hours,
    //  plus an additional $0.50 per hour begun after that
    return 2.00 + ceil(hours - 3) * 0.50;
  }
}
#包括
双倍计算费用(双倍小时)
{

如果(hours要回答您的查询,您应该研究您的变量类型。您使用hours作为in,但返回一个2.00,它是一个浮点数(也称为非整数)

#包括
双倍计算费用(双倍小时)
{ 
//要准确使用Math中的ceil函数,参数应为双精度!

double calculateTime=(hours-Ceil函数。你说的是“一小时的一部分”,但是你的函数需要一个
int
,它不能保存小数。你能详细说明你想要完成什么吗?我的错。我最初把它作为一个整数,然后把它切换为float,让它接受所有时间的输入。我只是忘了切换。谢谢你捕捉到它。
int-hours
应该是
double hours
,因为
ceil(hours-3)
如果
hours
是一个整数,那么它实际上没有任何作用。你完全正确!我将编辑我的帖子谢谢:)我已经很久没有做过C哈哈@frxstrem了。如果提供的答案在任何方面对你有帮助,或者实际上是你在寻找的,请将其标记为答案,以便将来其他人会知道!:)@centurion937
#include <math.h>

double calculateCharge(double hours)
{ 
 //To use accurately the ceil function from Math, the parameter should be a double!
  double calculateTime = ( hours <3) ? 2 : (2+ceil(hours-3)*0.50); 
  return calculateTime;
}