0

ABOUT PROGRAM

I'm creating a program that calculates how many weeks it takes for a person to lose weight, from the current weight to their target weight, given a weight loss of 1.38kg a week.

The program prompts the user for their current weight and their target weight and displays an invalid error message if the current weight or target weight (or both) are 0 or less.

The program will also check if the current weight is greater than target weight and display the appropriate error message if the current weight is not greater than the target weight.

MY PROBLEM

If the current weight is greater than the target weight, a loop should be performed to reduce the current weight by 1.38kg. The loop should continue until the current weight is less than or equal to the target weight. A counter should keep track of how many times the loop has been performed... this indicates the number of weeks it will take to reach the target weight...

BUT I EVERY TIME I RUN THE PROGRAM I DONT GET THE CORRECT RESULT.

Below is an example of 2 weights and the correct number of weeks.

Current weight: 87 Target weight: 64 Weeks: 17

var current_weight = 0.0
var target_weight = 0.0
var weeks = 0

current_weight = prompt("What is your current weight?")
target_weight = prompt("What is your target weight?")

if (current_weight > 0 && target_weight > 0) {
  if (current_weight > target_weight) {
    while (current_weight <= target_weight); {
      current_weight = (current_weight - 1.38);
      weeks = weeks + 1;
    }
    alert("It will take " + weeks + " weeks for you to achieve your target!")
  } else {
    alert("Your current weight must be MORE than the target weight!");
  }
} else {
  alert("Invalid entry.")
}

What did I do wrong??

1
  • 2
    your second if checks to see if the current weight is greater than the target weight, but the while loop only runs when the current weight is smaller than the target weight.
    – Pointy
    Nov 23, 2018 at 23:00

1 Answer 1

1

while (current_weight <= target_weight); Will run the loop while the current weight is below the target, which above says it cannot be, so the loop will never run. I reversed the symbol and it runs correctly.

var current_weight = 0.0
var target_weight = 0.0
var weeks = 0

current_weight = prompt("What is your current weight?")
target_weight = prompt("What is your target weight?")

if (current_weight > 0 && target_weight > 0) {
  if (current_weight > target_weight) {
    while (current_weight >= target_weight) {
      current_weight = (current_weight - 1.38);
      weeks = weeks + 1;
    }
    alert("It will take " + weeks + " weeks for you to achieve your target!")
  } else {
    alert("Your current weight must be MORE than the target weight!");
  }
} else {
  alert("Invalid entry.")
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.