0

I'm trying to write a basic programme, which gets a user's input, divides by seven, and then returns the result.

#include <cs50.h>
#include <stdio.h>

int main(void)
{
    int s = get_int("Input:  ");
    float f = (s / 7);
    printf("%f\n", f);
}

Eg. if I input "8", I would expect 1.142857. But I instead simply get "1.000000". Why is this?

Krishna Kanth Yenumula
  • 2,533
  • 2
  • 14
  • 26
BlueKhakis
  • 293
  • 1
  • 8
  • 1
    Look up "integer division" in C - basically, if you divide an integer, the result will also be an integer (floored). You'll want to cast `s` to a float first before dividing, e.g. `float f = (float)s / 7;` – dschurman Dec 05 '20 at 16:44
  • 3
    Or just `float f = (s / 7.0);` ?? – Adrian Mole Dec 05 '20 at 16:47
  • 2
    Does this answer your question? [Why does dividing two int not yield the right value when assigned to double?](https://stackoverflow.com/questions/7571326/why-does-dividing-two-int-not-yield-the-right-value-when-assigned-to-double) – Krishna Kanth Yenumula Dec 05 '20 at 16:59

1 Answers1

1
#include <stdio.h>
int main()
{
    int s=4;
    float f = ((float)s / 7);
    printf("%f\n", f);
    getch();
}

You just have to typecast the int to float. int/float division give you the floor of given integer whereas float/float division gives you float

Aniket Bose
  • 55
  • 1
  • 8