9

I'm working on an assignment and I'm getting this warning:

C4_4_44.c:173:2: warning: format ‘%f’ expects argument of type ‘float *’, 
but argument 2 has type ‘double *’ [-Wformat]

The variabled is declared in main as:

double carpetCost;

I'm calling the function as:

getData(&length, &width, &discount, &carpetCost);

And here's the function:

void getData(int *length, int *width, int *discount, double *carpetCost)

{

    // get length and width of room, discount % and carpetCost as input

    printf("Length of room (feet)? ");

    scanf("%d", length);

    printf("Width of room (feet)? ");

    scanf("%d", width);

    printf("Customer discount (percent)? ");

    scanf("%d", discount);

    printf("Cost per square foot (xxx.xx)? ");

    scanf("%f", carpetCost);

    return;

} // end getData

This is driving me crazy because the book says that you don't use the & in

scanf("%f", carpetCost); 

when accessing it from a function where you passed it be reference.

Any ideas what I'm doing wrong here?

  • 2
    You might want to read a [`scanf` reference](http://en.cppreference.com/w/c/io/fscanf). – Some programmer dude Feb 21 '14 at 21:02
  • 1
    This is intended for inconsistency with printf, in order that it's not easy to remember: `printf("%f", double_value)`; `scanf("%f", &float_value)`. – Kaz Feb 21 '14 at 21:04
  • @vaxquis just saw this after asking my question a long time ago and wanted to explain. I was taking a class, doing searches, and was frustrated because I did not know the correct search terms to use, so I was turning up nothing. Sorry if I gave the impression that I was trying to use the forum to do my homework for me. I'm actually an adult in his 50s who is a firm believer in doing his own work. Peace. – David Peterson Harvey Sep 05 '16 at 21:15

3 Answers3

11

Change

scanf("%f", carpetCost);

with

scanf("%lf", carpetCost);

%f conversion specification is used for a float * argument, you need %lf for double * argument.

ouah
  • 142,963
  • 15
  • 272
  • 331
3

Use %lf specification instead for double * argument.

scanf("%lf", carpetCost); 
haccks
  • 104,019
  • 25
  • 176
  • 264
1

Use %lf instead of %f if you are scanning a double type of variable. You can check this in detail also about %lf & %f from the discussed thread's link.

Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

Barnik Biswas
  • 354
  • 3
  • 8
RahulKT
  • 171
  • 4