Math calculation issue with Javascript - javascript

I am having a bit of trouble with a few math calculation in javascript.
The goal of this calculation is to generate a value when the user clicks on a text field.
For example:
1 Kilogram costs 32 cents to ship to America and the user wants to find out what 10KG will cost him which is $3.20. For this I have the following piece of javascript code:
function calculate(num) {
var weight = document.getElementById('weight'+num);
var price = document.getElementById('price'+num);
if(num == undefined || num == '' || num.length <= 0 || isNaN(weight.value) || isNaN(price.value)) return false;
if(num == 1) multiplyBy = 0.32;
if(num == 2) multiplyBy = 0.14;
if(num == 3) multiplyBy = 0.24;
if(num == 4) multiplyBy = 0.53;
var sum = parseInt(document.getElementById('weight'+num).value) * multiplyBy;
if(isNaN(sum)) return false;
price.value = sum;
}
The above code works perfectly fine, however when I reverse the process (someone has $3.20 and wants to find out how much KG he/she can ship with that (which is 10KG) the script returns: 9.375KG
The following code is used for this calculation:
function reverse(num) {
var weight = document.getElementById('weight'+num);
var price = document.getElementById('price'+num);
if(num == undefined || num == '' || num.length <= 0 || isNaN(weight.value) || isNaN(price.value)) return false;
if(num == 1) divideBy = 0.32;
if(num == 2) divideBy = 0.14;
if(num == 3) divideBy = 0.24;
if(num == 4) divideBy = 0.53;
var sum = parseInt(document.getElementById('price'+num).value) / divideBy;
if(isNaN(sum)) return false;
weight.value = sum;
}
I honestly don't grasp why it is failing, It would be much appreciated if someone could help me out with this.

var sum = parseInt(document.getElementById('price'+num).value) / divideBy;
You are forcing price into an integer before dividing it. So if price is 3.20, you are actually dividing 3 / 0.32, which is 9.375.
Don't force it into an integer.

Related

I have an error in my school javascript project

I have multiple errors in my code. When I run the code, it gives an error saying that there is an unexpected identifier. Here is the full error, "SyntaxError: Unexpected identifier at /script.js:46:16". However, when I check through lines 46 through 16, I cant find any unclosed functions or methods. When I comment the if statement on line 46, it just gives an error on the other if statement. Can someone help me?
Heres the code:
function print(str){
console.log(str)
}
function farhToKelvin(far){
const cel = Math.floor(far / (9/5) - 32)
const kel = cel + 273
return kel
}
function farhToCelsius(far){
const cel = Math.floor(far / (9/5) - 32)
return cel
}
function convertToFarh(type, val){
type.toLowerCase()
val.toLowerCase()
if (type == "kelvin"){
return Math.floor(far / (9/5) - 32 - 273)
}
else if(type == "celsius"){
return Math.floor(far / (9/5) - 32)
}
}
while (farh != "exit"){
var farh = prompt("enter a farhanhite tempature: ")
var type = prompt("convert it to celsius, or kelvin")
type.toLowerCase()
if (type == "celsius"){
const c = farhToCelsius(farh)
var val = convertToFarh(c)
if (val > 50 or val == 50){
print("it is cold, you should wear a coat")
}
if (val > 50 or val == 50){
print("it is hot, you should wear a tank top")
}
}
else if(type == "kelvin"){
const k = farhToKelvin(farh)
var val = convertToFarh(k)
if (val > 50 or val == 50){
print("it is cold, you should wear a coat")
}
if (val > 50 or val == 50){
print("it is hot, you should wear a tank top")
}
}
}
if (val > 50 or val == 50){
In Javascript, instead of or, we use ||. If you have a similar problem again, you might want to take a look at What does this symbol mean in JavaScript?
change
if (val > 50 or val == 50)
to this
if (val > 50 || val == 50)
or better to this
if (val >= 50)
there are similar problems on line 50 and 60 and 64
you need to update them all.
logically line 46 and 50 are the same. based on you print message the line 50 should be
if (val > 50 ) but line 45 should be if ( val <= 50)
so you have both syntax and semantic problems in your code to address
Here's a complete list of the issues you have in your code:
Using or instead of || (as others have stated)
Using incorrect variable name in the convertToFarh function
Omitting type parameter when calling convertToFarh
Attempting to call String.toLowerCase() on a number variable
Misspelling fahrenheit
Using or instead of || (Logical OR)
In your code, I believe you are intending to indicate if (val > 50 || val == 50) { instead of using or as used in other programming languages.
Before:
if (val > 50 or val == 50){
print("it is cold, you should wear a coat")
}
if (val > 50 or val == 50){
print("it is hot, you should wear a tank top")
}
After:
if (val > 50 || val == 50){
print("it is cold, you should wear a coat")
}
if (val > 50 || val == 50){
print("it is hot, you should wear a tank top")
}
This logic also doesn't make sense. Perhaps you mean value < 50 in the first one and val >= 50 in the second?
You also repeat yourself whether you're converting to/from Kelvin or Celsius, so that code could be extracted out into its own function or just reduce the if..else blocks down to only affect the necessary variables and perform the comparison after these blocks.
Using incorrect variable name in convertToFarh function
In the convertToFarh function, you reference a variable named far, but there's no variable by that name. So you either mean to reference the val argument or you are trying to reference the fahr variable declared outside the function. In my code, I assume the former is the case val and rename it as follows:
function convertToFarh(type, val){
type.toLowerCase()
val.toLowerCase()
if (type == "kelvin"){
return Math.floor(val / (9/5) - 32 - 273)
}
else if(type == "celsius"){
return Math.floor(val / (9/5) - 32)
}
}
Omitting type parameter when calling convertToFarh
In both function calls to convertToFarh, you use the c or k variable as the value of the val parameter, but you don't indicate the type. I have fixed this to indicate the type for each part:
var val = convertToFarh("celsius", c);
var val = convertToFarh("kelvin", k);
Attempting to call String.toLowerCase() on a number variable
In the convertToFarh function, you are attempting to call the String.toLowerCase() method on a number type (val) which gives an error. In my code, I simply commented this out and confirmed it can safely be removed.
Misspelling fahrenheit
It might not seem like a big deal, but making sure variables have proper spelling helps when others are reviewing your code (whether bug-fixing or general code review). I have fixed function names, variable names, and any references to fahrenheit in your code to be the proper spelling. This includes:
"enter a fahrenheit temperature: "
function fahrToKelvin and function calls
function fahrToCelsius and function calls
function convertToFahr and function calls
The variable named farh to fahr
Function parameters named far were changed to val to avoid variable name collision
Full code
function print(str) {
console.log(str);
}
function fahrToKelvin(val) {
const cel = (val - 32) / (9 / 5);
return Math.floor(cel + 273.15);
}
function fahrToCelsius(val) {
const cel = Math.floor((val - 32) * 5 / 9);
return cel;
}
function convertToFahr(type, val) {
if (type == "kelvin") {
return Math.floor(val / (5 / 9) - 459.67);
} else if (type == "celsius") {
return Math.floor(val / (9 / 5) + 32);
}
}
var fahr = prompt("enter a fahrenheit tempature: ");
var type = prompt("convert it to celsius, or kelvin");
type = type.toLowerCase();
if (type == "celsius") {
const c = fahrToCelsius(fahr);
var val = convertToFahr("celsius", c);
if (val < 50) {
print("it is cold, you should wear a coat");
}
if (val >= 50) {
print("it is hot, you should wear a tank top");
}
} else if (type == "kelvin") {
const k = fahrToKelvin(fahr);
var val = convertToFahr("kelvin", k);
if (val < 50) {
print("it is cold, you should wear a coat");
}
if (val >= 50) {
print("it is hot, you should wear a tank top");
}
}

making a point counter for a dice game in javascript

I am trying to make a dice game point counter where you are awarded points based on how close your guess of what you thought the number was going to be to what the number rolled is. My current code looks like this
function continueL(e){
if (e.keyCode == Keyboard.letter('L')){
add(copter);
var evorod = readInt("What number do you think it's going to be? You are guessing ");
println("Please click the die to roll a number");
mouseClickMethod(contin);
}
}
function contin(e){
var num = Randomizer.nextInt(1,12);
println("The number rolled is.... " + num);
var numText = new Text("The number rolled is...." + num, "20pt Arial");
numText.setPosition(50, 200);
numText.setColor(Color.red);
add(numText);
if (num == evorod){
println("Congrats! You Win! Here is 100 points");
} else {
if(num == evorod - 1 || num == evorod + 1){
println("So close! Here is 80 points!");
} else {
if(num == evorod - 2 || num == evorod + 2){
println("Almost got it. Take 60 points!");
} else {
if(num == evorod - 3 || num == evorod + 3){
println("Nice try. Take 40 points!");
} else {
if(num == evorod - 4 || num == evorod + 4){
println("Whoops... maybe next time? Take 20 points");
} else {
println("Better luck next time.");
}
}
}
}
}
remove(copter);
}
But it only displays the final else no matter what your guess was vs the number rolled.
edit: evorod is a global variable
evorod needs global scope, right now it only exists inside the continueL() function so will be undefined when you try to use it in contin(). Fix that by declaring it outside the function.
Meanwhile your if statements could be simplified to this, instead of a bunch of separate nested conditionals:
if (num == evorod) {
println("Congrats! You Win! Here is 100 points"); // there is no println in javascript, I'll assume you've coded your own equivalent
} else if (num == evorod - 1 || num == evorod + 1) {
println("So close! Here is 80 points!");
} else if (num == evorod - 2 || num == evorod + 2) {
println("Almost got it. Take 60 points!");
} else if (num == evorod - 3 || num == evorod + 3) {
println("Nice try. Take 40 points!");
} else if (num == evorod - 4 || num == evorod + 4) {
println("Whoops... maybe next time? Take 20 points");
} else {
println("Better luck next time.");
}
Try a switch statement instead. There are 6 possible outcomes per throw. If you guessed less or more than the actual outcome you lose 20 points per digit away from the true outcome.
First of all, let's find how off your prediction was from the roll. We do that by subtracting (excuse my shabby math).
int outcome = ...
int guess = ...
int difference;
if(outcome > guess)
difference = outcome - guess;
else if(outcome < guess)
difference = guess - outcome;
switch(difference)
{
case 0:
{
System.out.println("100 Wondred points!");
break;
}
case 1:
{
System.out.println("You get 80 hamsters!");
break;
}
}
And so on it goes, with a difference of 5 being the lowest score because it means you were 5 numbers away from the outcome.

Prime Number Function in Javascript ...multiple statements

So I'm tasked with making program that can tell whether a number is prime or not. I want to solve this problem using a multiple if-statement. The one that I came up with is awkward. So i just want some feedback on how to make it better.:
function primenumber(num) {
if (num / num === 1 && num % 2 !== = 0 || num % 3 !== = 0 | num % 5 !== = 0 | num % 7 !== = 0) {
return true;
} else {
return false
}
}
I figured these numbers are the lowest common denominators. So a number is prime if these numbers don't divide evenly into it. Any feedback is greatly appreciated. Keep in mind that I am new to Javascript.
I figured it out:
If((num === 1) || (num === 2) || (num === 3) || (num === 5) || (num === 7))
{ return true;
}
If((num%2===0) || (num%3===0) || (num%5===0) || (num%7===0)){
return false;}
}
return true;
}
It may not be the most sophisticated coding but it's mine and it works perfectly.. at least according to coderbyte

Program that uses While and For loops to find all Prime Numbers between an upper Bound

I'm having some trouble with the for loop. I have the while loop working properly, but I need help with the nested loop. The concept of loops is fairly new to me and I don't quite understand what I've done here in the code. Any help would be greatly appreciated.
var number = parseInt(window.prompt("Enter number: ", ""));
var divisor;
var check;
var prime = true;
var num;
document.write("The factors of ", number, " are: </br>");
divisor = 1;
while (divisor <= number) {
check = number % divisor;
if (check == 0) {
document.write(divisor, " ");
if ((divisor != 1) && (divisor != number)) {
prime = false;
}
}
divisor = divisor + 1;
}
if (prime == true) {
document.write("<br>The number is prime");
} else {
document.write("<br> The number is composite");
}
Something to get you excited. This program is using for and while to check prime numbers. The for loop is used as an if-check but this will work. You should also try using functions to minimize your code.
var number = parseInt(window.prompt("Enter number: ", ""));
var result = isPrime(number);
function isPrime(number) {
var start = 2;
//USING WHILE
while (start <= Math.sqrt(number)) {
if (number % start++ < 1) return false;
}
return number > 1;
}
//USING FOR
for (;result;){
document.write("<br>The number is prime");
}
if(!result) {
document.write("<br>The number is NOT prime");
}
As a fresh man,I think may you need a break in the while loop,beacause you just check if it is prime once.Just like that:
if((divisor != 1) && (divisor != number)){
prime= false;
break;
}

Javascript Fizzbuzz Issue

I'm trying to do some simple tests to help further my javascript knowledge (which is quite fresh). Goal 1 is to print numbers from 1-100 that aren't divisible by 5 or 3.
I tried the following:
for (var i = 1; i <= 100; i ++)
{
if (i%3 !== 0 || i%5 !== 0){
console.log(i);
}
}
This logs EVERY number from 1-100, and I can't tell why. Probably the simplest simplest questions here but it's doing my head in!
I think you mean &&, not ||. With ||, you're basically testing to see if the number is not divisible by 3 or by 5 - only if a number is divisible by both do you reject it (in other words, multiples of 15).
The typical answer to FizzBuzz is:
if( i%3 == 0 && i%5 == 0) FizzBuzz
elseif( i % 3 == 0) Fizz
elseif( i % 5 == 0) Buzz
else number
So to get directly to the number you need for i%3==0 to be false AND i%5==0 to be false. Therefore, you want if( i%3 !== 0 && i%5 !== 0)
Here's a quite simple FizzBuzz function that accepts a range of numbers.
function fizzBuzz(from, to) {
for(let i = from; i <= to; i++) {
let msg = ''
if(i % 3 == 0) msg += 'Fizz'
if(i % 5 == 0) msg += 'Buzz'
if(msg.length == 0) msg = i
console.log(msg)
}
}
fizzBuzz(1, 25)
As for a more complex solution, that's one way you could define a higher order function which generates customized FizzBuzz functions (with additional divisors and keywords)
function fizzBuzzFactory(keywords) {
return (from, to) => {
for(let i = from; i <= to; i++) {
let msg = ''
Reflect.ownKeys(keywords).forEach((keyword) => {
let divisor = keywords[keyword]
if(i % divisor == 0) msg += keyword
})
if(msg.length == 0) msg = i
console.log(msg)
}
}
}
// generates a new function
const classicFizzBuzz = fizzBuzzFactory({ Fizz: 3, Buzz: 5 })
// accepts a range of numbers
classicFizzBuzz(1, 25)
const extendedFizzBuzz = fizzBuzzFactory({ Fizz: 3, Buzz: 5, Bazz: 7, Fuzz: 11 })
extendedFizzBuzz(1, 25)
I attacked this the same was as Niet the Dark Absol:
for (var n = 1; n <= 100; n++) {
if (n % 3 == 0 && n % 5 == 0)
console.log("FizzBuzz");
else if (n % 3 == 0)
console.log("Fizz");
else if (n % 5 == 0)
console.log("Buzz");
else
console.log(n);
}
However, you can also do it this way:
for (var n = 1; n <= 100; n++) {
var output = "";
if (n % 3 == 0)
output += "Fizz";
if (n % 5 == 0)
output += "Buzz";
console.log(output || n);
}
One of the hardest parts of learning JavaScript - or any language - for me is understanding solutions can come in many ways. I like the first example more, but it's always good to keep thinking and look at other options.

Categories

Resources