Heres my simple html source
<html>
<head>
<title>
Dec2Bin
</title>
<script type="text/javascript">
function app() {
var decimal = prompt("Numero en Decimal");
alert("El numero " + decimal + " en codigo binario es igual a " + dec2bin(decimal));
}
function dec2bin(decimal) {
var binario = "";
while (decimal != 0) {
if (decimal % 2 == 0) {
binario += "1";
}
else {
binario += "0"
}
decimal = decimal / 2
}
return binario;
}
</script>
</head>
<body>
<input type="button" onclick="app()" value="Procesar" />
</body>
</html>
Avg keeps telling me its a virus.. if I remove the javascript it stops... what can I do?
You appear to have an endless loop because decimal will never equal 0. I could see where AVG might not like this.
function dec2bin(decimal) {
var binario="";
while(decimal!=0) {
if(decimal % 2==0)
binario+="1";
else
binario+="0"
}
decimal/=2
return binario ;
}
I did a quick google search and pulled up a cleaner function:
function dec2bin(dec) {
var bits = [];
var remainder = 0;
while (dec >= 2) {
remainder = dec % 2;
bits.push(remainder);
dec = (dec - remainder) / 2;
}
bits.push(dec);
bits.reverse();
return bits.join("");
}
I'm not 100% sure if this is the cause, but your while-loop:
while(decimal!=0)
{
if(decimal % 2==0)
binario+="1";
else
binario+="0"
}
doesn't terminate because decimal doesn't change until outside the loop. Thus, running that loop should lock up your browser.
The only other thing I can see in your updated code is that your prompt does not coerce decimal to a number.
If the user doesn't input a number, decimal/2 will return NaN, which will never equal zero, so your loop won't terminate. I would suggest using parseInt to convert to an integer, and then if that returns NaN, you could either assign 0 to decimal or find some other way to skip your while-loop (such as changing your while-loop's condition to decimal != 0 || decimal != NaN.
I doubt that an anti-virus would pick that up, but it's not impossible.
Whilst it would be lovely if AV tools could automatically solve the halting problem(!), it is likely just another in a long string of false positives from today's utterly hopeless anti-virus industry. Maybe renaming some variables and moving the code about a bit would stop it in the short term, but in general false positives are a tiresome fact of life for any programmer.
The only other thing to check is: is AVG detecting that exact source posted above in a local file with nothing else in it as a virus? For me, AVG at virustotal is not flagging such a file as suspicious. Does it only detect it online? If so you would need to inspect the View->Source to see that there hasn't been a compromise on your server unexpectedly injecting a malicious script into the page at serve-time.
Best thing to do is uninstall AVG. Virus scanners are a scam, and they significantly reduce the performance of your machine. If you're really worried about malware, best thing to do is install ubuntu as the main OS of your machine and run windows inside a VM such as virtual box.
Related
I have a problem with the following exercise:
Enter N number of numbers by prompt. Show the average of the 1-digit numbers entered. End the program with the word “exit"/"salir”.
I also have to do the average calculation with a function. Here's what I have:
let i;
var sum = 0;
var avg = 0;
var average = function(i) {
sum = sum + i;
avg = sum/(i+1);
}
do {
i = prompt("Ingrese un numero: ");
if ((i < 10) && (i > -10)) {
average(i);
}
} while (i !== "salir");
alert(`el promedio de los numeros de un solo digito es: ${avg}`);
I tried limiting the program by stating that the average function will only be executed for one digit numbers, but the problem is that this is giving me the total average of all the numbers entered not the average of only the 1 digit numbers.
You've succeeded in avoiding including multi-digit numbers from the sum and average. The problem isn't in that, it's here:
avg = sum/(i+1);
That's not how averages work. An average is the sum divided by how many values went into making that sum. (The number of numbers you added to sum.)
Keep track of how many numbers you added to sum, and use that count to calculate the average.
Side note: A couple of notes on the code, just for what they're worth:
Your code is currently relying on implicit conversion from string (what the user types in) to number (what you use with sum). Although it works in this example, I strongly recommend doing the conversion explicitly. My other answer here (also on SO) lists your various options for doing that.
You've used both let and var in your code. I suggest never using var, it has no place anymore in modern JavaScript. Use let if you need to let the variable's value change (as with sum), and const when you don't.
You're missing one ; (after the assignment statement assigning to average). (You can rely on Automatic Semicolon Insertion if you like [I don't recommend relying on it, but some others do], but whichever way you go, it's best to know the rules and then consistently do or don't include your ;.)
I suggest declaring your variables in the innermost scope you can declare them in. There's no reason for i to be global in your code, just make it local to the do-while loop body.
Obviously in a very simple exercise like this it's mostly fine, but I recommend not getting used to prompt and alert, they're relics from the 1990s and behave in very unusual (and sometimes problematic) ways compared to most functions in JavaScript.
var i;
var sum = 0;
var avg = 0;
var average = function(num) {
sum = sum + num;
i+=1
avg = sum/i;
}
var ans;
do {
ans = prompt("Ingrese un numero: ");
if ((ans < 10) && (ans > -10)) {
average(ans);
}
} while (ans !== "salir");
alert(`el promedio de los numeros de un solo digito es: ${avg}`);
Should remove this but will leave it here for any future visitors.
Scenario :
Attempted to create this troll 'guessing game program'.
It prompts the user to guess a number between 1-10, and the user will
get it wrong each time until they guess all numbers, frustrated, I
tell them to guess one last time, upon this attempt, it says your
answer was right!
Code - I am new at JS so I have not really gone into DOM manipulation and the code for some reason does not work.
<!DOCTYPE html>
<html>
<head>
<title>Guessing Game</title>
</head>
<body>
<script type="text/javascript">
var numset = 0;
var guess = numset + 1;
var max = numset >= 11;
while (guess !== max) {
prompt("I am guessing a number between 1-10, let's see if you can guess it!");
} else {
alert("You Won! Number of guesses: 11")
}
</script>
</body>
</html>
Todo :
Please correct this
or Suggest any better approach, i am open to options.
Thank You.
One option would be to use a Set of numbers between 1 and 10, prompt for a number and remove it from the set until the set is empty, and then display the total number of guesses.
Note that because the program uses prompt, it will block the user's browser - consider using something less user-unfriendly, like an input and a button / enter listener, if at all possible.
// Set of numbers from 1 to 10:
const numSet = new Set(Array.from(
{ length: 10 },
(_, i) => i + 1
));
let guesses = 1; // to account for the final guess at the end
while(numSet.size > 0) {
const guessed = prompt("I am guessing a number between 1-10, let's see if you can guess it!");
numSet.delete(Number(guessed));
guesses++;
}
prompt("I am guessing a number between 1-10, let's see if you can guess it!");
alert("You Won! Number of guesses: " + guesses)
EDIT
I tested something out, and apparently, this:
if(info.max.value == "") {maxdesiredvalue = 999999999999999999999}
Returns in the chrome console:
> maxdesiredvalue
< 999999999
So I believe the problem really comes from there... is there a maximum number of digits we can attribute to a variable?
I'm into javascript for a few months now, and I've made a program that generates random weapons for a tabletop rpg.
Every weapon generated has a price relative to it's attributes. My problem today is that this price won't exceed 9 digits (cannot reach billion), even though it can.
In my generator, it is possible to choose certain properties before generating the weapon. If I intentionally try to generate something worth over a billion gold, it will crash instantly. On the other hand, if there is any way the weapon can be generated without exceeding the billion, it will do so.
For example, the most expansive metal is the "Residuum". The only 2 weapons that can be generated in Residuum are the dart and the shuriken, since they only use 1/16 of an Ingot. Therefore if I set the metal to be Residuum, they will be the only 2 possible generated weapons. From this point, if I try to specify I want a Residuum Sword, it will simply crash as explained earlier.
In my generation options, I also have a text input for the user to choose a minimum value and/or a maximum value for the weapon. I set the default max value to Infinity, so it should'nt be a problem.
function desiredvalue(){
if(info.max.value == "") {maxdesiredvalue = Infinity}
else {maxdesiredvalue = parseInt(info.max.value)}
if(info.min.value == "") {mindesiredvalue = 0}
else {mindesiredvalue = parseInt(info.min.value)}
}
In my html:
Min price: <input type="text" name="min" value="" onchange="desiredvalue()">
Max price: <input type="text" name="max" value="" onchange="desiredvalue()">
I already tried to deactivate this function to see if it was the problem, but even without a specific max value, weapons still won't be generated if their value exceeds 9 digits.
Maybe the problem sets inside the value formula, so here it is, even though it might not be a big help since it is all made up from variables.
WeapValue = ((((IngotValue * Ingots) + CraftTime + (actualEnchantTime * 3) + (LS * 0.02) + (R * 0.05) + BS + (FTH * 0.03)) * (((BPArace + BPAstatus + BPAlevel + ((BPAcrit1 + 1) * BPAcrit2)) / 100) + 1)) + PAenchant + PAaugment1 + PAaugment2 + PAaugment3)
Also the value is modified afterwards to fit in gold, silver or copper...
WeapValue.toLocaleString('en-US', {minimumFractionDigits: 0});
WeapValue = WeapValue.toFixed(2);
if (WeapValue >= 2) {WeapValue2 = Math.ceil(WeapValue); goldtype = " GP"}
else if (WeapValue < 2 && WeapValue >= 1) {WeapValue2 = WeapValue * 10; goldtype = " SP"}
else if (WeapValue < 1 && WeapValue >= 0) {WeapValue2 = WeapValue * 100; goldtype = " CP"}
Nothing else in the script really change the value, and all the variables affecting it are defined earlier, and I don't really think they are the problem, since they actually seem to work (they simply make the price exceed 9 digits).
If you have any questions related to the script, I'm here to answer, but I can't put the full script since it is very, very long (2543 lines)...
If anyone has an idea of how I can deal with my problem, it would be so appreciated! Again, I'm not a javascript expert, but I did my best and looked a lot on the Internet for help, but I still can't get rid of this problem...
Thank you!
Here is the question im trying to address and here is what I have. I am not sure what i've done wrong but it will not run in WebStorm:
alert("This is question 1");
var rndmNum = Math.rndmNum();
rndmNum = rndmNum * 100 + 1;
var i = 0;
do {
var rndmNum = prompt;
function guessNum(guess) {
if (guess < rndmNum);
}
alert("Your guess is too low");
} else if (guess > rndmNum) {
alert("Your guess is too high");
}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Question 1</title>
</head>
<body>
<h1>Question 1</h1>
<p>
This is a page used to run/execute some JavaScript.
</p>
<p>
Next question.
</p>
<p>
Return home.
</p>
</body>
</html>
does anyone see any problems in what I have done or have any recommendations? Feedback is appreciated thanks
There's a syntax error:
function guessNum(guess) {
if (guess<rndmNum);
}
alert ("Your guess is too low");
}
else if (guess>rndmNum) {
alert("Your guess is too high");
}
Should be:
function guessNum(guess) {
if (guess<rndmNum) {
alert ("Your guess is too low");
}
else if (guess>rndmNum) {
alert("Your guess is too high");
}
}
You have an else if when your if statement was separated by an alert.
Also
Your brackets {} do not properly close.
The do is not syntactically correct or needed.
Math.rndmNum() is not a real method, think you want Math.random()
I only briefly looked at it. I don't really approve of giving answers for homework questions, but I will pose a question for you.
What if someone puts in something besides a number? You check if the answer is lower or higher, but you never make sure that it's actually a number.
You might want to consider either validating that the answer being checked is a number before checking it, or checking only for the answer you're looking for.
Also, var i = 0. I'll assume that you're going to use that later in your code, but i is pretty much a universal JavaScript variable.
What you're doing there is setting the global variable i to = 0, and most likely you're going to change that somewhere else in your code. Then you might run a for loop that rewrites i, or you might have an extension that rewrites it.
Consider naming your variables more uniquely, or keep the scope of the variables that aren't unique to functions or loops.
first of all. if you want to generate random number use:
Math.random() because Math.rndmNum is undefined
prompt is function and to use it you should write:
var rndmNum = prompt('geuss a number');
to convert random number from float to integer:
rndmNum = Math.floor(rndmNum * 100 +1);
and do-while loop should be:
do {
var rndmNum = prompt('geuss a number');;
function guessNum(guess) {
if (guess<rndmNum){
alert ("Your guess is too low");
}else if (guess>rndmNum) {
alert("Your guess is too high");
}
}
i++;
}while(i<10) // number of guesses
I've written a JavaScript program that calculates the depth of a binary tree based on the number of elements. My program has been working fine for months, but recently I've found a difference when the web page is viewed in Chrome vs Firefox.
In particular, on Firefox:
Math.log2(8) = 3
but now in Chrome:
Math.log2(8) = 2.9999999999999996
My JavaScript program was originally written to find the depth of the binary tree based on the number of elements as:
var tree_depth = Math.floor(Math.log2(n_elements)) + 1;
I made a simple modification to this formula so that it will still work correctly on Chrome:
var epsilon = 1.e-5;
var tree_depth = Math.floor(Math.log2(n_elements) + epsilon) + 1;
I have 2 questions:
Has anyone else noticed a change in the precision in Chrome recently for Math.log2?
Is there a more elegant modification than the one I made above by adding epsilon?
Note: Math.log2 hasn't actually changed since it's been implemented
in V8. Maybe you remembered incorrectly or you had included a shim that
happened to get the result correct for these special cases before Chrome
included its own implementation of Math.log2.
Also, it seems that you should be using Math.ceil(x) rather than
Math.floor(x) + 1.
How can I solve this?
To avoid relying on Math.log or Math.log2 being accurate amongst different implementations of JavaScript (the algorithm used is implementation-defined), you can use bitwise operators if you have less than 232 elements in your binary tree. This obviously isn't the fastest way of doing this (this is only O(n)), but it's a relatively simple example:
function log2floor(x) {
// match the behaviour of Math.floor(Math.log2(x)), change it if you like
if (x === 0) return -Infinity;
for (var i = 0; i < 32; ++i) {
if (x >>> i === 1) return i;
}
}
console.log(log2floor(36) + 1); // 6
How is Math.log2 currently implemented in different browsers?
The current implementation in Chrome is inaccurate as they rely on multiplying the value of Math.log(x) by Math.LOG2E, making it susceptible to rounding error (source):
// ES6 draft 09-27-13, section 20.2.2.22.
function MathLog2(x) {
return MathLog(x) * 1.442695040888963407; // log2(x) = log(x)/log(2).
}
If you are running Firefox, it either uses the native log2 function (if present), or if not (e.g. on Windows), uses a similar implementation to Chrome (source).
The only difference is that instead of multiplying, they divide by log(2) instead:
#if !HAVE_LOG2
double log2(double x)
{
return log(x) / M_LN2;
}
#endif
Multiplying or dividing: how much of a difference does it make?
To test the difference between dividing by Math.LN2 and multiplying by Math.LOG2E, we can use the following test:
function log2d(x) { return Math.log(x) / Math.LN2; }
function log2m(x) { return Math.log(x) * Math.LOG2E; }
// 2^1024 rounds to Infinity
for (var i = 0; i < 1024; ++i) {
var resultD = log2d(Math.pow(2, i));
var resultM = log2m(Math.pow(2, i));
if (resultD !== i) console.log('log2d: expected ' + i + ', actual ' + resultD);
if (resultM !== i) console.log('log2m: expected ' + i + ', actual ' + resultM);
}
Note that no matter which function you use, they still have floating point errors for certain values1. It just so happens that the floating point representation of log(2) is less than the actual value, resulting in a value higher than the actual value (while log2(e) is lower). This means that using log(2) will round down to the correct value for these special cases.
1: log(pow(2, 29)) / log(2) === 29.000000000000004
You could perhaps do this instead
// Math.log2(n_elements) to 10 decimal places
var tree_depth = Math.floor(Math.round(Math.log2(n_elements) * 10000000000) / 10000000000);