1

In a code written by me, I have used both below functions to calculate mod of displayed negative number.

fmod(-10,11)
(-10, 11)

Though the correct answer is 1. It always displays the answer -10 in c++. How I can solve it?

2

1 Answer 1

4

From cppreference.com:

double fmod (double numer, double denom);
The floating-point remainder of the division operation x/y calculated by this function is exactly the value x - n*y, where n is x/y with its fractional part truncated.
The returned value has the same sign as x and is less than y in magnitude.

In your case it is -10 - (-10)/11 * 11 = -10 - 0 * 11 = -10, which is correct for that implementation of fmod. If you need another answer, you should implement your own version, as modulo is defined in different ways for negative numbers.

4
  • 8
    cplusplus.com is not "C++ Reference", due to multiple mistakes inside it. cppreference.com is, since it, at least tries to follow C++ standard as closely, as possible. Jun 4, 2020 at 8:43
  • My bad, took a look at the tab name, where it says "fmod - C++ Reference".
    – whiskeyo
    Jun 4, 2020 at 8:44
  • Due to the reasons mentioned: you should avoid linking new users to a site with potential mistakes, instead of an actual C++ reference. Jun 4, 2020 at 8:45
  • usually I am reluctant to discredit the work of many with good intentions, but I can confirm, it happened just too often that I was mislead by wrong/incomplete information, till now I never had such experience on cppreference Jun 4, 2020 at 9:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.