-5

To Explain my question in a better I want to know the nearest integer less than the given value. Now this value is of double type...So there are two cases

  1. if value contains decimal part that is if value is 6.8 the answer would be 6
  2. if value is already integer than the answer should be one less that is if value is 6 then answer would be 5

Now simply taking floor would not apply to the second case So I tried this ceil(value-1) but here again I encountered a problem that is when value was 0.3 it should output 0 but it was outputting -0(negative zero). So what is the best way to implement this?

Jarod42
  • 203,559
  • 14
  • 181
  • 302
Naman
  • 353
  • 3
  • 14
  • 1
    Show us your code and we can help. We can't start from scratch and write it for you. – nicomp Aug 30 '19 at 13:36
  • @nicomp I have already explained my question – Naman Aug 30 '19 at 13:37
  • 5
    You don't understand SO. Post code and we help. We don't write a new program based on your specs. – nicomp Aug 30 '19 at 13:39
  • What exactly is the problem with negative zero? Negative zero is the same value as zero, after all. – Aziuth Aug 30 '19 at 13:40
  • So you need to check whether the float holds an integer value, then you truncate it, and if it as an integer value, you decrease it by one. The duplicate will tell you how to check if the float represents an integer value. – Blaze Aug 30 '19 at 13:40
  • @Blaze Yeah you got it right that's what i want to ask but isn't there a better way? – Naman Aug 30 '19 at 13:44
  • @Blaze And what about -0(negative zero), cause ceil(value-1) will also do the same work if its integer it will simply reduce by 1 and if it contains float value it will reduce by one then take the ceil.. – Naman Aug 30 '19 at 13:46
  • Which programming language are you using? That matters in questions like this one, such as the "minus zero" problem. That would be solved in many languages with `ceil(value - 1) + 0`. – Rory Daulton Aug 30 '19 at 13:47
  • @RoryDaulton c++14 – Naman Aug 30 '19 at 13:48
  • I'm not sure, but in the end something like `int a = f - (ceilf(f) == f);` should do the trick. Maybe test that with a couple of values to see if it works. – Blaze Aug 30 '19 at 13:50

1 Answers1

1

As told in the comments, you can see how to check if a number is an integer or not, and perform an appropriate action: Checking if float is an integer.

However, if you want more interesting way, without any conditions:

float a;
float result;
cin >> a;
result = std::floor(a) - !std::ceil(a - std::floor(a)); // ceil(a - 1) <--- As told in @Naman comment, it's a better way.
cout << result << endl;
Coral Kashri
  • 3,436
  • 2
  • 10
  • 22