Can't use modulus on doubles?
The %
operator is for integers. You're looking for the fmod()
function.
#include <cmath>
int main()
{
double x = 6.3;
double y = 2.0;
double z = std::fmod(x,y);
}
modulus is not working when using doubles in c++
The modulus operator %
is an integral function.
You need to use fmod
for floating-point.
How do I use modulus for float/double?
You probably had a typo when you first ran it.
evaluating 0.5 % 0.3
returns '0.2' (A double) as expected.
Mindprod has a good overview of how modulus works in Java.
Why does modulus division (%) only work with integers?
Because the normal mathematical notion of "remainder" is only applicable to integer division. i.e. division that is required to generate integer quotient.
In order to extend the concept of "remainder" to real numbers you have to introduce a new kind of "hybrid" operation that would generate integer quotient for real operands. Core C language does not support such operation, but it is provided as a standard library fmod
function, as well as remainder
function in C99. (Note that these functions are not the same and have some peculiarities. In particular, they do not follow the rounding rules of integer division.)
Related Topics
How to Output Coloured Text to a Linux Terminal
Return Statement VS Exit() in Main()
C++ Performance Challenge: Integer to Std::String Conversion
What's the Difference Between _Pretty_Function_, _Function_, _Func_
Why Can't I Initialize Non-Const Static Member or Static Array in Class
Undefined Behavior and Sequence Points Reloaded
Using Opencv and Svm With Images
Is There a Replacement For Unistd.H For Windows (Visual C)
What Is the Fastest Way to Transpose a Matrix in C++
How Does #Include ≪Bits/Stdc++.H≫ Work in C++
How to Use Break to Exit Multiple Nested 'For' Loops
C++11 Reverse Range-Based For-Loop
Are Members of a C++ Struct Initialized to 0 by Default
Difference Between These (Bcondition == Null) and (Null==Bcondition)
Why Does Optimisation Kill This Function
How to Initialize Base Class Member Variables in Derived Class Constructor
What How to Use Instead of the Arrow Operator, '-≫'
Qt5 Static Build Yields Failed to Load Platform Plugin "Windows"