Lucky500
Lucky500

Reputation: 507

if condition not executing past second block

I am trying to work on this problem (in JavaScript first), later I will have to convert to C for CS50, but my output is stuck after the 2nd if statement. In an idea scenario, the problem would work until it reaches 0. The problem is occurring when one of the conditions is not being met and it jumps to the following if/else statement ...but I am not sure why is not computing.

function greedy(){
  var change = prompt("How much do I owe you? ");
  var counter = 0;
  var div, rem;
  var quarter = 0.25;
  var dime = 0.10;
  var nickel = 0.5;
  var penny = 0.1;
  if (change > quarter){
    div = Math.floor(change / quarter);
    rem = parseFloat((change % quarter).toFixed(3));
    counter += div;
      console.log(counter);
      console.log(rem);
  } 
  if (rem > dime && rem !== 0){
    div = Math.floor(rem / dime);
    rem = parseFloat((rem % dime).toFixed(3));
    counter += div;
    console.log(counter);
    console.log(rem);
  }
  else if (rem > nickel && rem !== 0){
    div = Math.floor(rem / nickel);
    rem = parseFloat((rem % nickel).toFixed(3));
    counter += div;
    console.log(counter);
    console.log(rem);
  } 
  else if (rem > penny && rem !== 0) {
    div = Math.floor(rem / penny);
    rem = parseFloat((rem % penny).toFixed(3));
    counter += div;
    console.log(counter);
    console.log(rem);
  } else {
    console.log(counter);
  }

  
}

greedy();

Upvotes: 0

Views: 56

Answers (3)

Seva
Seva

Reputation: 2488

1) Convert it to cents and use integer arithmetic. It probably won't byte you in javascript, but in C it definitely will.

2) nickel is 0.05, not 0.5, and penny is 0.01

3) else if , should be if. And last else should be if (rem !== 0).

4) all > comparisons should be >=. E.g. if (rem > dime && rem !== 0) should actually be if (rem >= dime && rem !== 0), otherwise 25 cents will be given as 2 dimes and a nickel, not as a quater.

Upvotes: 0

Automated
Automated

Reputation: 67

if your are trying to check condition of 2nd if statement when change > quarter then insert 2nd if statement inside 1st if statement. For change < quarter insert 2nd if statement inside 1st else statement.

Upvotes: 0

Paul
Paul

Reputation: 2206

At first glance, these are wrong:

var nickel = 0.5;
var penny = 0.1;

Corrected:

var nickel = 0.05;
var penny = 0.01;

Upvotes: 2

Related Questions