C: How do I make a number always round up

孤街浪徒 提交于 2019-12-13 08:45:17

问题


I'm wanting to make a function that calculates a cost based on time. For any time less than three hours, it would return a flat rate charge of $2. For each hour or part of an hour over that, it would charge an additional $0.50. Hours are input by user as a float data type to 2 decimal places. How can I make it to where it will always round up the time to a whole hour? Here's the code I have so far for the function:

int calculateCharges(float hours)
{
 if (hours <= 3){
    return 2.00
}
else

回答1:


First of all, you use the data type int, which cannot hold fractional values (and will implicitly round them towards zero, even before the function is ever called.) You should use double instead, since this is the proper datatype for fractional numbers.

You would also want to use the ceil(x) function, which gives the nearest whole number larger than or equal to 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;
  }
}



回答2:


To answer your query, you should study your variable type. You use hours as a in, but you return a 2.00 which is a floating number( aka not a integer)

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

Include the math.h header to be able to use the Math struc. It is a really help structure when you have to compute values, you can calculate the sinus of a number for instance. In our situation, the ceil function will always return the value to round up to the nearest integer. You can learn more about it here : http://www.techonthenet.com/c_language/standard_library_functions/math_h/ceil.php Oh and also, you said less than three hours, but in your function you say less or equals to 3. Make sure you actually use the good operator or you could end up with results you are not expecting while running your function!

Oh, you can look up the ternary operator there in order to have a better understanding of it since it's a bit obscure the first time :http://msdn.microsoft.com/en-us/library/ty67wk28.aspx

Hope it helps you :)



来源:https://stackoverflow.com/questions/26444658/c-how-do-i-make-a-number-always-round-up

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!