Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my float print out as 0 even though I input 13.5 for it using scanf?

Tags:

c

scanf

I'm having trouble figuring out why my float variable keeps printing out 0 when I input it as a number.

Code:

int num, month, day, year;
float price[10000];


printf("Enter item number: \n");
scanf("%d", &num);
printf("Enter unit price: \n");
scanf("%f", &price);
printf("Enter purchase date (mm/dd/yyyy): \n");
scanf("%d/%d/%d", &month, &day, &year);

printf("Item\t\tUnit\t\tPurchase\n");
printf("    \t\tPrice\t\tDate\n");
printf("%d      ", num);
printf("$%.2f     ", price); 
printf("      %d/%d/%d\n", month, day, year);
return 0;

I input 555 for my item number, 13.5 for my price, and 10/24/2010 for my date. When I did this it printed out that my price was $0.00. It does this for any number I input. Why?

like image 285
MoreFoam Avatar asked Jan 28 '15 20:01

MoreFoam


2 Answers

You can not insert array value like this -

scanf("%f", &price);

Use a for loop to insert values into the array price -

for(i=0; i<sizeWhatYouWant; i++){
 scanf("%f", &price[i]);
}

Or just change the declaration float price[10000] to -

float price;
like image 126
Razib Avatar answered Sep 20 '22 01:09

Razib


Just change this:

float price[10000];

to this:

float price;

Because you use it as a single variable and not as an array

like image 30
Rizier123 Avatar answered Sep 19 '22 01:09

Rizier123