user5221548
user5221548

Reputation:

Trouble with C functions, specifically in calculation

// 6.1 Brain Teaser

#include <stdio.h>

int pills,weight;
float bottlenumber;

void load ()
{
     printf("Enter the number of pills: ");
     scanf("%d", &pills);
     printf("Enter the weight of your pills: ");
     scanf("%d", &weight);
}

void calc ()
{
     bottlenumber = (weight - 210) / (float)0.1;
}

void print()
{
     printf("The bottle number is %.f!", bottlenumber);
}

void main()
{
    load();
    calc();
    print();
}

The user is suppose to enter 211.3. The answer then is suppose to be 13 but instead I get 10. I think it has to do with float aspect and the calculation part.

Upvotes: 0

Views: 60

Answers (2)

user3629249
user3629249

Reputation: 16540

this line is the problem:

bottlenumber = (weight - 210) / (float)0.1;

remember, the value entered for weight is 3.

so 3 - 210 = -207

next divide -207 by 0.1 which = -2070

I suspect the line should be written somewhat differently

Upvotes: 0

dbush
dbush

Reputation: 223972

weight is an int, not a float, and you're reading it in a as an int, so if the user enters 211.3 then weight contains 211.

If you expect weight to be a float then you should declare it as such and read it in as such.

float weight;

...

printf("Enter the weight of your pills: ");
scanf("%f", &weight);

Upvotes: 1

Related Questions