C Programming - Declarations and Initializations - Discussion

Discussion Forum : Declarations and Initializations - General Questions (Q.No. 1)
1.
Which of the following statements should be used to obtain a remainder after dividing 3.14 by 2.1 ?
rem = 3.14 % 2.1;
rem = modf(3.14, 2.1);
rem = fmod(3.14, 2.1);
Remainder cannot be obtain in floating point division.
Answer: Option
Explanation:

fmod(x,y) - Calculates x modulo y, the remainder of x/y.
This function is the same as the modulus operator. But fmod() performs floating point divisions.

Example:


#include <stdio.h>
#include <math.h>

int main ()
{
  printf ("fmod of 3.14/2.1 is %lf\n", fmod (3.14,2.1) );
  return 0;
}

Output:
fmod of 3.14/2.1 is 1.040000

Discussion:
141 comments Page 2 of 15.

Silambu said:   7 years ago
No @Keerthi.

The floating point remainder cannot be obtained by modulo operator.
(1)

Keerthi said:   7 years ago
Option A is correct.

Varadaraj said:   7 years ago
As per my knowledge, it is option A.

Prerna said:   7 years ago
fmod is not working in GCC compiler. How can I use this in GCC compiler?

Please suggest me to get the output of this.

S.sasindra said:   7 years ago
Option A is also correct becuase;

int rem=3.14/2.1;
printf("%d",rem);
return();

Piyush said:   7 years ago
Why option A is incorrect?

Shahi said:   7 years ago
What is the function %lf here?

Venkat said:   8 years ago
#include<stdio.h>
#include<math.h>
main()
{
float a=1.2,b=2.3,c;
c=a%b;
printf("%f\n",fmod(a,b));
}
~

Test1.c:6:4: error: invalid operands to binary % (have \'float\' and \'float\')
user@user:~/c/test$

I have tested in GCC it gives error so finally conclusion is % this operator not possible for floating points

Nayan said:   8 years ago
What is the meaning of %lf ? Or why not use %f only?

Subrat said:   8 years ago
@Dinesh Kumar.

#include<stdio.h>
int main()
{
int a=1;
printf("%d %d %d",a,a++,++a);
return 0;
}
Output : 3 2 3.
But logically 3 2 2.

Can any explain how 3 2 3 comes?

Your logic is true,function data passing is from right to left. So first ++a execute then a++,then a.
But the current value of a will be substitute in pre-increment operator always.
So the output will be 3 2 3.


Post your comments here:

Your comments will be displayed after verification.