Reputation: 5684
I have a program for a C class I need to write. The program asks for a quantity, and I need to multiply that quantity by another variable which the user inputs. Basic calculator script for a c class :)
I have it set up like this,
int qty; //basic quantity var
float euro, euro_result;
//assign values to my float vars
euro = .6896; //Euro Dollars
euro_result = euro * qty; // Euro Dollars multiplied by user input qty
//start program for user
printf("Enter a quantity: ");
//alow user to input a quantity
scanf("%d", &qty);
printf("Euro: %f \n", euro_result);
Why does it not work as expected?
Upvotes: 2
Views: 17053
Reputation: 16024
The problem is that you're multiplying the qty
by the exchange rate before the user has inputted any data.
Upvotes: 0
Reputation: 3481
You have multiply the euro with user given quantity qty before entered by the user. It should be as below: //euro_result = euro * qty; // <-- shift this to the position given below
//start program for user
printf("Enter a quantity: ");
//alow user to input a quantity
scanf("%d", &qty);
euro_result = euro * qty; // Euro Dollars multiplied by user input qty
printf("Euro: %f \n", euro_result);
Thats all.
Upvotes: 2
Reputation: 217341
The statements in a C program are executed sequentially, and expressions are not evaluated symbolically. So you need to reorder your statements this way:
int qty;
float euro, euro_result;
euro = .6896; // store constant value in 'euro'
printf("Enter a quantity: ");
scanf("%d", &qty); // store user input in 'qty'
euro_result = euro * qty; // load values from 'euro' and 'qty',
// multiply them and store the result
// in 'euro_result'
printf("Euro: %f \n", euro_result);
Upvotes: 7
Reputation: 28110
I suspect you want to calculate euro_result = euro * qty;
only after you have gathered the value for qty.
Upvotes: 2
Reputation: 75215
The bug is that the line
euro_result = euro * qty;
needs to be after qty is read-in
Upvotes: 7