I need my code to only accept whole numbers, no decimals and should prompt an error when a decimal gets entered. I don't want a new function , I'm hoping I can just add lines to my function but I don't know what I need to add.
function number_function() {
number = parseInt(prompt('Enter a positive integer:'));
if (number < 0) {
alert('Error! Factorial for negative number does not exist. But I will show you the positive number');
number = number * -1;
let n = 1;
for (i = 1; i <= number; i++) {
n *= i;
}
alert("The factorial of " + number + " is " + n + ".");
} else if (number === 0) {
alert("Please enter a number greater than 0");
} else {
let n = 1;
for (i = 1; i <= number; i++) {
n *= i;
}
alert("The factorial of " + number + " is " + n + ".");
}
}
number_function();
You can do this to check if the number has decimals
const val = 10.7 % 1;
if (val !== 0) {
console.log('has decimals');
} else {
console.log('has no decimal');
}
JavaScript provides the built-in function Number.isInteger(n)
Related
I need to prompt the user to enter a series of numbers, or the word "quit".
Then, If the user enters a number, add the new number to a running total.
And, If the user enters the word "quit" the loop should stop execution.
I cant figure what should I do here. Im a beginner. i don't know how to make it work when user enter a word quit
let total = 0;
let number = 0;
do {
total += number;
number = parseInt(prompt('Enter a number: '));
if (number >= 0) {
document.writeln("<p>You entered " + number + "!</p>");
} else {
if (isNaN(number)) {
number = parseInt(prompt('Enter a number: '));
document.writeln("<p>Try again. We are looking for a number!</p>");
}
}
} while (number >= 0)
document.writeln("<p>The total is " + total + "</p>")
Use break to stop the javascript loop:
let total = 0;
let number = 0;
do {
total += number;
text = prompt('Enter a number: ');
if (text == "quit") {
break;
}
number = parseInt(text);
if (number >= 0) {
document.writeln("<p>You entered " + number + "!</p>");
} else {
if (isNaN(number)) {
number = parseInt(prompt('Enter a number: '));
document.writeln("<p>Try again. We are looking for a number!</p>");
}
}
} while(number >= 0)
document.writeln("<p>The total is " + total + "</p>")
So I'm fairly new to JavaScript but I cannot seem to find the average in my code. I want to understand why my average is not working. Any help you guys?
function getEvenOdd() {
var oddSum = 0;
var evenSum = 0;
var num = 0;
var evenAvg = 0;
var oddAvg = 0;
while (true) {
num = parseInt(prompt("Enter a number(-1 to exit)"));
if (num == -1) {
break;
}
if (num % 2 == 0) {
evenSum += num;
} else {
oddSum += num;
}
evenAvg = evenSum / num;
oddAvg = oddSum / num;
}
alert("Sum of all even numbers is: " + evenSum);
alert("Sum of all odd numbers is: " + oddSum);
alert("Average of all even numbers is : " + evenAvg);
alert("Average of all odd numbers is: " + oddAvg);
}
On your code, to calculate the oddAvg and evenAvg, you have divided evenSum and oddSum by num variable (which is input from prompt).
And as you know, average = total sum / total count, so it's not right to divide the sum by the input number variable.
Instead of that, you need to calculate the count of odd and even numbers and divide the even and odd sum by the even and odd number counts as follows.
function getEvenOdd() {
var oddSum = 0;
var evenSum = 0;
var num = 0;
var evenAvg = 0;
var oddAvg = 0;
var evenCount = 0;
var oddCount = 0;
while (true) {
num = parseInt(prompt("Enter a number(-1 to exit)"));
if (num == -1) {
break;
}
if (num % 2 == 0) {
evenSum += num;
evenCount ++;
} else {
oddSum += num;
oddCount ++;
}
}
evenAvg = evenSum / evenCount;
oddAvg = oddSum / oddCount;
alert("Sum of all even numbers is: " + evenSum);
alert("Sum of all odd numbers is: " + oddSum);
alert("Average of all even numbers is : " + evenAvg);
alert("Average of all odd numbers is: " + oddAvg);
}
getEvenOdd();
These operations are dividing the evenSum or oddSum by the last input num.
evenAvg = evenSum / num;
oddAvg = oddSum / num;
You should divide the sum by the number of even or odd inputs.
Instead of evenSum / num use evenSum/Count of Numbers entered.
How about this solution? It is aiming to store odd and even numbers into oddList and evenList.
function getEvenOdd() {
var evenAvg = 0;
var oddAvg = 0;
var oddList = [];
var evenList = [];
var num = 0;
while (true) {
num = parseInt(prompt("Enter a number(-1 to exit)"));
if (num == -1) {
break;
}
if (num % 2 == 0) {
evenList.push(parseInt(num));
} else {
oddList.push(parseInt(num));
}
evenAvg = evenList.reduce((p, c) => p + c, 0) / evenList.length;
oddAvg = oddList.reduce((p, c) => p + c, 0) / oddList.length;
}
alert("Sum of all even numbers is: " + evenList.length);
alert("Sum of all odd numbers is: " + oddList.length);
alert("Average of all even numbers is : " + evenAvg);
alert("Average of all odd numbers is: " + oddAvg);
}
getEvenOdd();
I have a program that needs to convert integers to binary and decimal. I have the binary portion working but am stuck on the decimal part. I'm trying to use intToFloat but not sure if that's right. Here is the code for the conversion functions.
if (cT[0].checked) {
// to binary
var dval = parseInt(val);
if (isNaN(dval)) {
alert("input value is not a number");
}
else if ((val % 1) !== 0 ) {
alert("number is not a integer");
}
else if (dval < 0) {
alert("Input value must be a positive integer");
}
else {
convertByArray(dval);
}
}
else if (cT[1].checked) {
//to decimal
var dval = parseFloat(val);
if (isNaN(dval)) {
alert("input value is not a number");
}
else if ((val % 1) !== 0 ) {
alert("number is not a integer");
}
else if (dval < 0) {
alert("Input value must be a positive integer");
}
else {
intToFloat(dval);
}
}
else {
alert("Please select a conversion type.");
}
}
function convertByArray(dval) {
var rA = new Array();
var r,i,j;
i=0;
while (dval > 0) {
r = dval % 2;
rA[i] = r;
var nV = (dval - r) / 2;
$("txtCalc").value = $("txtCalc").value + " Decimal " + dval + " divided by 2 = "
+ nV + " w/Remainder of: " + r + "\n";
i += 1;
dval = nV;
}
for(j=rA.length-1; j>= 0; j--) {
$("txtOut").value = $("txtOut").value + rA[j];
}
}
function intToFloat(num, decPlaces) {
return num + '.' + Array(decPlaces + 1).join('0');
}
I need it to show the output of an integer being converted to a decimal and show the value as well, like it already does when it converts to binary.
parseInt(value, fromBase).toString(toBase)
To convert it to binary
parseInt(25,10).toString(2) //<== '25' is the value, 10 is the current base. 2 is the base you want to converted.
To convert it to decimal
parseInt(100011,2).toString(10)
To convert it to float
var num = 203
num.toFixed(6) // asnwer will be 203.000000
My goal is to create a program that checks whether the user input is a perfect number or not. It has validation for the numbers entered. If the input IS a perfect number, I'd like to print out each of the divisors. I tried using this method:
{
for(int number=2; number <= 10000 ; number++)
perfect(number);
return 0;
}
void perfect(int number)
{
int total = 0;
for (int i = 1; i < number; i++)
{
if (number % i == 0)
total += i;
}
if (number == total)
{
for (int x = 1; x < number; x++)
{
if (number % x == 0)
cout << x << " + ";
}
cout << " = " << number << endl;
}
}
However, I was unable to get the desired effect. I am very new to javascript and am struggling with inserting code in the correct way. Does anyone have a suggestion for how I can get the desired effect? Here is the code I have already written:
function check_prime() {
var input = document.getElementById("enteredNumber").value;
var number = parseInt(input);
if (isNaN(number)) {
alert("Oops! Please enter a valid number.");
document.getElementById("enteredNumber").value="";
document.getElementById("result").innerHTML = "";
document.getElementById("enteredNumber").focus();
}
else if (input.length === 0) {
alert("Please enter a number.");
document.getElementById("enteredNumber").focus();
}
else if (!isNaN(number)) {
if (is_perfect(number)) {
document.getElementById("answer").innerHTML = "Congratulations! " + number + " is a perfect number." ;
}
else {
document.getElementById("answer").innerHTML = "I'm sorry. " + number + " is not a perfect number. Try Again.";
}
}
else {
document.getElementById("answer").innerHTML = "Please enter a number.";
}
}
function is_perfect(number)
{
var temp = 0;
for(var i=1;i<=number/2;i++)
{
if(number%i === 0)
{
temp += i;
}
}
if(temp === number)
{
return true;
}
else
{
return false;
}
}
function clear_textbox(){
document.getElementById("answer").innerHTML = "";
document.getElementById("enteredNumber").value="";
document.getElementById("enteredNumber").focus();
}
I'd suggest revising your is_perfect() function to return an array of divisors if the number is perfect and null if the number is not perfect. Then the calling code has the divisors available for display when the input is a perfect number.
function is_perfect(number) {
var temp = 0;
var divisors = [];
for(var i=1;i<=number/2;i++) {
if (number%i === 0) {
divisors.push(i);
temp += i;
}
}
return temp === number ? divisors : null;
}
Then:
var divisors = is_perfect(number);
if (divisors) {
document.getElementById("answer").innerHTML = "Congratulations! " + number + " is a perfect number.";
// display the divisors somewhere; the alert is just for show
alert("Divisors: " + divisors.toString());
} else {
...
}
[Note: In an earlier version of this answer, I had initialized temp to 1 and divisors to [1] and had started the loop at 2, on the theory that 1 is always a divisor. Unfortunately, that's wrong, since 1 is not a proper divisor of 1. The revised version of is_perfect() now returns null for an argument of 1 instead of [1]. An alternative fix would have been to test explicitly for the case number === 1, but that's uglier (if perhaps a tiny bit more efficient, since it avoids one % evaluation).]
so I use 2^(n-1)*(2^n -1) formula (to generate a perfect number) and checking if last digit is 6 or 8 to check if x is perfect number.
Note: It's not perfect 100%
function pn(x) {
x = '' + x
for (var i = 0; i < Infinity; i++) {
perfnumgen = Math.pow(2, i - 1) * (Math.pow(2, i) - 1)
if (x === "" + perfnumgen && (perfnumgen % 10 === 8 || perfnumgen % 10 === 6))
return true
else if (perfnumgen > x)
return false
console.log("" + perfnumgen)
}
}
Question, how do I make it so when an user-inputted number is negative, it isn't added to the total variable that will be ouput?
Code below!
function lab10logicInLoopsPart1()
{
lCounter = 1;
var total = 0;
userNumber = 0;
while(lCounter < 6) {
lCounter++;
userNumber = prompt("Enter a number.");
total += +userNumber;
document.write("Entered number was: " + userNumber + "\n");
}
document.write("\nTotal: " + total);
}
After prompting the user to enter a number, just check it's not a negative with an if statement:
if(userNumber >=0)
{ //do your stuff here}