Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

The bug is that the line

euro_result = euro * qty;

needs to be after qty is read-in

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);

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top