Grocery Store Part 1

I have been trying to troubleshoot, but I can’t figure out why my compiler is printing out:
“An apple costs: $1.49, there are 23 in inventory found in section: F and your customers gave it an average review of 21908%!”

I don’t know why it isn’t making the proper review number available as a conversion from double to int. I am new to coding any solution to this could help. Thank You


int main() {

  int appleQuantity;
  double applePrice = 1.49;
  double appleReview = 82.5;
  int appleReviewDisplay;
  const char appleLocation = 'F';

  appleQuantity = 23;
  appleReview = (int)appleReviewDisplay;
  

// Put all your code above this and if you declare your variables using the given names and types there is no need to change any of the code below.
printf("An apple costs: $%.2f, there are %d in inventory found in section: %c and your customers gave it an average review of %d%%!", applePrice, appleQuantity, appleLocation, appleReviewDisplay);

}

Hello,
I have the same problem.

You wrote:

double appleReview = 82.5;
int appleReviewDisplay;

You have declared and initialized appleReview as a double with a value of 82.5
Then, you have declared appleReviewDisplay as an int but have not yet assigned a value to it.

There are a number of issues in the following statement:

appleReview = (int)appleReviewDisplay;

You are casting appleReviewDisplay to an int and then assigning it to appleReview.
When assigning values to variables, the basic syntax is

// Correct
variable = value;

// Incorrect 
value = variable

The value to be assigned is to the right of the = assignment operator, and the variable to which the value is being assigned is to the left of the = operator.
Furthermore, since appleReviewDisplay is uninitialized, so this can cause undefined behavior. Depending on the programming language, uninitialized variables may be assigned default values OR they may contain some garbage value OR your program may crash OR your output may keep changing randomly.

What you want to do is:

double appleReview = 82.5;
int appleReviewDisplay;

appleReviewDisplay = (int)appleReview;

appleReview holds a double value of 82.5. In the last line, we cast this double value into an int and then assign the resulting integer to appleReviewDisplay. We have already declared appleReviewDisplay as as uninitialized int earlier in the code, so we don’t need to make any new declaration. We just need to assign an int value to the variable. The casting of appleReview from double to int provides the value of the desired data type.
After the correction above, your program should show the output:

“An apple costs: $1.49, there are 23 in inventory found in section: F and your customers gave it an average review of 82%!”

1 Like