2021年2月7日星期日

Unsure how to round integers in C++

I am new to C++, so I'll do my best to explain my problem. I'm trying to output rounded values after the user inputs a low value and high value. The thing is that the output will only show the incremented values (and possibly zero as well). Here is how the increments are determined:

inputDifference = high - low;    if (inputDifference <= 10)      increment = 1;  else if (inputDifference <= 50)      increment = 5;  else if (inputDifference <= 100)      increment = 10;  else      increment = 20;  

For example, if the user inputs 0 for the low and 100 for the high, it will output values 0 to 100 only in increments of 10, 0 and 100 included (0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100).

I'm having difficulty figuring out how to handle when the user inputs float values. I have to use floor() and ceil() to accomplish this somehow. Here is the criteria for rounding:

  • If the low input is less than 1.0 from the preceding increment, assign the preceding increment's value to it. Otherwise, assign the value of the next increment.
  • If the high input is 1.0 or less from the next increment, assign the next increment's value to it. Otherwise, assign the value of the previous increment.

Sample inputs (low, high) and outputs:

Input: 1, 5 (therefore, increment = 1)

Output: 1.0, 2.0, 3.0, 4.0, 5.0

Input: 0.9, 20 (therefore, increment = 5)

Output: 0.0, 5.0, 10.0, 15.0, 20.0

Input: 1.1, 20 (therefore, increment = 5)

Output: 5.0, 10.0, 15.0, 20.0

Input: 1, 150 (therefore, increment = 20)

Output: 20.0, 40.0, 60.0, 80.0, 100.0, 120.0, 140.0

How can I apply floor() and/or ceil() here?

https://stackoverflow.com/questions/66094763/unsure-how-to-round-integers-in-c February 08, 2021 at 09:12AM

没有评论:

发表评论