user1877731
user1877731

Reputation: 35

Trying to get the remainder from modulus but having some troubles - in C

Updated with a created modulus function. However, while it does compile, after entering two numbers, it returns nothing.

#include<stdio.h>
int main(){
    double num1, num2, num3;
    printf("Enter two double numbers > ");
    scanf("%lf", &num1);
    scanf("%lf", &num2);
    num3 = num2;
    while (num3 > num1) {
        if (num3 > num1) {
        num3 = num3-num1;
        }
        else {
            printf("%.4lf float modulo %.4lf is %.4lf", num1, num2, num3);
        }
    }
    return 0; 
}

Upvotes: 0

Views: 101

Answers (2)

chux
chux

Reputation: 153303

After accept answer

Simply calculate the quotient, make the quotient a whole number and the calculate the modulus. Depending on what definition of modulus you use, may want if (x > 0) instead of if (q > 0)

double fmod1877731(double x, double y) {
  double q = x/y;
  if (q > 0) q = floor(q);
  else q = ceil(q);
  return x - y*q;
}

void fmodtest(double x, double y) {
  double z0 = fmod(x,y);
  double z1 = fmod1877731(x,y);
  printf("x:% e y:% e z0:% 0.20e z1:% 0.20e\n", x,y,z0,z1);
}

int main(void) {
  fmodtest(10.0,3.0);
  fmodtest(10.0,-3.0);
  fmodtest(-10.0,3.0);
  fmodtest(-10.0,-3.0);
  fmodtest(10.0,1.23);
  fmodtest(10.0,15);
}

Upvotes: 0

Daniel
Daniel

Reputation: 6745

As you know, division is really just a shortcut form of subtraction, and a remainder is the part of the number that is left over when you divide. So consider repeatedly subtracting num2 from num1 until you have a number that is less than num2. That's your modulus. I'll leave the code up to you.

Example: 7 % 3:

7 - 3 = 4
4 - 3 = 1

1 < 3, so 7 % 3 = 1

Upvotes: 1

Related Questions