Finding Modulo Problem

Hello guys. I need help in finding the modulo/remainder of the two numbers (which also includes numbers in decimal and negative format). I wonder what's wrong with my code below. Can someone lend me a hand in fixing my code below and explain to me what's wrong with my code and how to deal with it.

#include <iostream>
#include <iomanip>
#include <math.h>

using namespace std;

int main()
{
    double num1;
    double num2;
    
    cout << "Enter First Number: ";
    cin >> num1;
    
    cout << "Enter Second Number: ";
    cin >> num2;
    
    cout << "\n The result is " << num1 % num2;

    return 0;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
using namespace std;

int main()
{
   double num1, num2;
   cout << "Enter first number: ";   cin >> num1;
   cout << "Enter second number: ";  cin >> num2; 
   int quotient = num1 / num2;
   double remainder = num1 - quotient * num2;
   cout << "Quotient: " << quotient << "    Remainder: " << remainder <<'\n';
}


Enter first number: 12.6
Enter second number: 3.8
Quotient: 3    Remainder: 1.2




You could also use remquo(), from <cmath>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
   double num1, num2;
   cout << "Enter first number: ";   cin >> num1;
   cout << "Enter second number: ";  cin >> num2;
   
   int quotient;
   double remainder = remquo( num1, num2, &quotient );
   cout << "Quotient: " << quotient << "    Remainder: " << remainder <<'\n';
}




Please use code tags, not output tags, for code snippets.


What you do for negative inputs depends a bit on your working definition; there are various alternatives.
Last edited on
The remainder operator does not work on floating-point types, the library function fmod provides that functionality.
https://en.cppreference.com/w/c/numeric/math/fmod
Tnx for the help guys. I appreciate that. I just post this as a reference in dealing with other problems that will be related to that. This will act as a reference to me in dealing with problems that are related to that.
Last edited on
Topic archived. No new replies allowed.