tags:

views:

366

answers:

5

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?

+7  A: 

The bug is that the line

euro_result = euro * qty;

needs to be after qty is read-in

mjv
+2  A: 

I suspect you want to calculate euro_result = euro * qty; only after you have gathered the value for qty.

ewall
+7  A: 

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);
dtb
Ah! So put it after the user has selected the qty and it should work. DUH! I am so stupid I did not even think of that.
HollerTrain
Don't worry. It's a common beginner's mistake.
dtb
a beginner? What gave it away? :)
HollerTrain
It's a common beginner's reaction to think they're stupid :-)
dtb
is it ok for me to post my finished code on here to have people critique? if not is there an ideal location on the web? i am always seeking gurus to lend me their five minutes...
HollerTrain
Go ahead. You can always edit your question to add more information or to show us your finished code. Just don't post it as an answer. And if you have a follow-up question, feel free to open another question.
dtb
yep, it's common when you come from lisp
gpilotino
+2  A: 

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.

Sadat
A: 

The problem is that you're multiplying the qty by the exchange rate before the user has inputted any data.

Alexsander Akers