1

input example : 356

356/100, is suppused to be 3.56

But I'm getting 3.0000000000, I'm using ideone online compiler for C.

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

int main() {
    int n;
    double frac;
    scanf("%d", &n);
    frac = (n/100);
    printf("%lf", frac);


    return 0;
}
Goun2
  • 417
  • 1
  • 11
  • 22

4 Answers4

3

That's because here frac = (n/100); you are doing plain integer arithmetic (as n is declared as an int and 100 is interpreted as an int (any whole number is taken to be an int unless specified otherwise)). What you need to do is say explicitly that you want to do an arithmetic operation with digits after decimal point. One way is to use a cast: frac = ((double) n/100);

If you don't use the cast, the division will be performed as you expect, but then the digits after the decimal point will be dropped. Since frac is declared as a double, 0s would get tacked on to the end.

babon
  • 3,615
  • 2
  • 20
  • 20
  • That solved and and it really makes since, I came from other languages and that wouldn't be needed, anyways, thank you. – Goun2 Jul 10 '17 at 04:45
  • 1
    @Goun2 Well, in C everything is explicit. You have to always keep how the bits and bytes are arranged in your head. Once you get that, IMHO, you will see how beautiful C is. – babon Jul 10 '17 at 04:47
2

In C, the result of division of two integer numbers (e.g. int, short, long) is also an integer (it is counter-intuitive, but it is implemented this way for performance reasons). As a result, the result of 5/2 is 2 and not 2.5. This rule is only for integer numbers. So, if you need to get a floating-point result, at least one of the numbers in a division operation must be of a floating-point type.

In case of your code, if you use 100.0 instead of 100, you will get the desired result. Also you can use casts or define n as double. This should work:

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

int main() {
    int n; // You can define n as double but don't forget to modify scanf accordingly. 
    double frac;
    scanf("%d", &n);
    frac = (n/((double)100)); // Or, frac = (n/100.0)
    printf("%lf", frac);


    return 0;
}
MxNx
  • 1,342
  • 17
  • 28
0

You cannot call division using integers to be double without declaring it.

For example int / int will result int.

Try declaring n as double

double n; scanf("%lf", &n); frag = n/100;

vahvero
  • 525
  • 11
  • 24
-2

input data type is an integer.

just change it to double or float to fix this problem.

int main() {
    double n;
    double frac;
    scanf("%d", &n);
    frac = (n/100);
    printf("%lf", frac);
    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70