It'sRainingMen
It'sRainingMen

Reputation: 183

Displaying Decimal places of a floating point in C

Here i have some simple code, used to calculate speed given a distance and time.

Since we have a division, a float variable is required, however, in my program below, it won't display correctly.

#include <stdio.h>
#include <conio.h>

int NewDR=0;
float NewSR=0;
int NewTR=0;


int main()
{ 
    printf("What is your new distance?");
    scanf("%d",&NewDR);

    printf("What is your new time?");
    scanf("%d",&NewTR);

    //NewSR = NewDR/NewTR;
    NewSR = (float)NewDR/(float)NewTR; //-Fix is here, thanks

    printf("Speed: %.2f",NewSR);

    getch();
}

Input:

Distance: 20
Time: 3

Expected output:

Speed = 6.67

Actual output :

Speed = 6.00

Upvotes: 1

Views: 79

Answers (3)

Manjunath N
Manjunath N

Reputation: 1375

Integer Number divided by Integer results in Integer. More Over you Need to Type-Caste it Explicitly. Implicit Conversion happens only when you are using from higher the Hierarchy to lower hierarchy (Ex: from flot->int).

Hence use NewSR = (double) NewDR/NewTR;

It will work out for you.

Upvotes: 0

Spikatrix
Spikatrix

Reputation: 20244

In NewDR/NewTR , since both the operands is an integer,an integer division is performed which yields an integer(in your case, 20/3=6) and is then assigned to NEWSR. For performing a floating point division,just cast any one of the variables into a float like this:

NewSR =(float) NewDR/NewTR;

Upvotes: 3

Sourav Ghosh
Sourav Ghosh

Reputation: 134326

change NewSR = NewDR/NewTR; to NewSR = ((float)NewDR)/((float)NewTR);

Before arithmatic operation, you need to have either of the operands in float, otherwise, the operation will take place as ints and the final result will be promoted to float [based on the target storage data type.]

Upvotes: 1

Related Questions