Overclock.net banner

Help in C programming

838 views 10 replies 6 participants last post by  RAND0M1ZER  
#1 ·
Hey there. Im taking a beginners course in c programming and i'm stuck. Im trying to add an integer and double, but the sum is showing only the integer value and not the result? here's the code:

int main (void)
{
// declare variables
int a;
double b;
double purchasePrice;

printf("\nNumber of items purchased\n");
scanf("%d",&a);

// (printf)Prompt user for number of items

// Take user input for number of items (scanf)

printf("\nEnter the Unit Price\n");
scanf("%.2f",&b);

// (printf) Prompt for unit price

// take user input for unit price (scanf)
purchasePrice = a + b;
printf("\nPurchase Price is %.2f\n",purchasePrice);
 
#4 ·
It's nice to add an explanation.

Why cast? Because you're adding a integer to a double and the compiler will automatically cast the double to integer, losing all decimal cases, and returning an integer to the purchaseValue. When specifically casting the integer to a double, (double) a, you're saying to the compiler to treat a as a double instead of an integer, in that specific operation.
 
#6 ·
If you try printing b directly after your scanf call, you will see that b is actually zero no matter what value you enter. This is because you are telling scanf to interpret the input as a float, but you are trying to store it in a double.

You must use %lf in your scanf to read the input as a double. Alternatively, you can store your numbers as floats instead of doubles (the precision difference won't matter for your code).

To everyone suggesting a cast. The integer will be automatically promoted to a float in the addition, so the cast has no effect.

ps. Please use code tags in future
smile.gif
 
#7 ·
Code:

Code:
int main(void) {
        int a;
        double b;

        printf("\nNumber of items purchased\n");
        scanf("%d", &a);;

        printf("\nEnter the Unit Price\n");
        scanf("%lf", &b);

        printf("\nPurchase Price is %.2lf", a + b);
}
That should work for you, the problem was you need to use %lf for doubles (long float), %f is for float.
 
#11 ·
Quote:
Originally Posted by adridu59 View Post

Quote:
Originally Posted by RAND0M1ZER View Post

That should work for you, the problem was you need to use %lf for doubles (long float), %f is for float.
Noticed that too but what I didn't understand is why "%.2lf" and not just "%lf".
%.2lf should also work. The only difference is the number of decimal places that are displayed. If you don't specify like with %lf, it will display all the decimal places.