Multiply a variable by another variable?

I have a program for a C class that I need to write. The program asks for a quantity, and I need to multiply that quantity by another variable that the user enters. Basic script calculator for class c :)

I set it 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 isn't it working as expected?

+2


source to share


5 answers


You have multiplied the euro with a user-specified amount of qty before being entered by the user. It should be as follows: // euro _result = euro * qty; // <- shift this position to the position indicated 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);

      



That's all.

+2


source


The error is that the line

euro_result = euro * qty;

      



should be after reading qty

+7


source


Statements in a C program are executed sequentially , and expressions are not evaluated symbolically . Therefore, you need to change the order of your statements as follows:

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

      

+7


source


I suspect you euro_result = euro * qty;

only want to calculate after you have collected the value for qty.

+2


source


The problem is that you multiply the value qty

on the exchange rate before the user enters any data.

0


source







All Articles