No, he does not change, there is no way he can change. Actually the silver question of a wrong premise.
In everything you do in a code you need to understand everything that is happening. In particular in using functions need to read the documentation completely before using it. In the case of prompt()
function) is not a command) the documentation says that the return of it is a data of type string
. That makes all the difference. If the return is a text and you try to make an arithmetic account with it will not happen what you expect. So your first code is completely different from the second, one calculates numbers and the other calculates texts.
Since you still want to operate on numbers, you need to convert the result of prompt()
into numbers. Assuming that you use values with a decimal point and that no precision is required in the calculation, you can use the parseFloat()
". What will you do before you use it?
The code could look like this:
var ap3questoes = (5 - (parseFloat(prompt("Nota da ap1")) + parseFloat(prompt("Nota da ap2"))) * 0.3) / 0.16;
document.write(ap3questoes * 0.4);
document.write(Math.round(ap3questoes));
So that's it? No, there are still problems. Like I said it only works if you do not want accuracy, try different numbers and you will see that there are cases that do not give the number you want. And it has nothing to do with prompt()
, but with float
type that is not suitable for accuracy , then it gives error even with the direct number. Most programmers ignore this and have their wrong codes unnoticed for years.
There is a misalignment of information displayed on screen in both codes, it is secondary, but it is good to make it clear that there is.
Finally, what if the person types an invalid format? A correct code can not require the person to type certain to work, unless he enters it after validating. Of course, it does not make a miracle, it will not fix the problem, but your code needs to identify that there was a typo, such as a letter being typed, or a wrong point. It would look something like this:
function teste() {
var t1 = prompt("Nota da ap1");
if (isNaN(t1)) return;
var t2 = prompt("Nota da ap2");
if (isNaN(t2)) return;
var ap3questoes = (5 - (parseFloat(t1) + parseFloat(t2)) * 0.3) / 0.16;
document.write(ap3questoes * 0.4);
document.write(" - ");
document.write(Math.round(ap3questoes));
}
teste();