I am writing a Babylonian algorithm for computing the square root of a positive number, and the iteration should keep going until the guess is within 1% of the previous guess.
the code that I have written gets the iteration going to the one before error is 1%. how can I make it to do one more iteration ?
to get the question straight, is there a way to tell it iterate untill the error is <1% ?
import java.util.Scanner;
public class sqrt {
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
System.out.print("\nplease enter the desired positive number in order to find its root of two: ");
double num = kb.nextDouble();
double guess=0;
double r, g1, error;
if (num>=0){
guess = num/2;
do{
r = num/guess;
g1 = guess;
guess = (guess+r)/2;
error = (guess-g1)/guess;
if (error<0){
error = -error;
}
}
while(error>0.01);
System.out.println("The square root of the number " + num +" is equal to " +guess);
} else {
System.out.println("Sorry the number that you entered is not a positive number, and it does not have a root of two");
}
}
}
Add a new counter that only gets increased in the (former) exit loop condition.
int exit = 0;
do {
...
if (error <= 0.01) {
exit++;
}
} while (exit < 2);
If you want to return a value only when the error is strictly less than 1%, you need to change the while condition.
Changing it to error >= 0.01 says "iterate, even when error is exactly equal to 1%, so we get a final error less than 1%".
Also, your if (num <= 0) allows a division by zero to happen, when num is exactly zero.
Let's check:
num = 0;
guess = num / 2; // guess = 0
r = num / guess; // r = 0 / 0
Looking at the below code should give you a clearer idea. I've commented it.
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("\nPlease enter the desired positive number in order to find its root of two: ");
double num = kb.nextDouble();
double guess=0;
double r, g1, error;
// Previous code allowed a division by zero to happen.
// You may return immediately when it's zero.
// Besides, you ask clearly for a *positive* number.
// You should check firstly if the input is invalid.
if (num < 0) {
System.out.println("Sorry the number that you entered is not a positive number, and it does not have a root of two");
}
// Since you assigned guess to zero, which is the sqrt of zero,
// you only have to guess when it's strictly positive.
if (num > 0) {
guess = num/2;
// Notice the slight change in the while condition.
do {
r = num/guess;
g1 = guess;
guess = (guess+r)/2;
error = (guess-g1)/guess;
if (error < 0) {
error = -error;
}
} while(error >= 0.01);
}
// Finally, print the result.
System.out.println(
"The square root of the number " + num +
" is equal to " + guess
);
}
Related
The application should print the first n odd numbers, where n is between 1 and 25, starting at start. start is between 100 and 200 and it says where the odd number sequence should start. If start is an even number then the sequence should start at the next odd number.
Here is and example with n = 4 and start = 193:
193, 195, 197, 199
The application must allow the user to enter values for n and start. It must then verify that n is between 1 and 25 and start is between 100 and 200.
My code so far:
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int n = sc.nextInt();
Scanner sc2= new Scanner(System.in);
int start = sc2.nextInt();
for (int i=start; i=n; i=start+1+=2)
if ((n>=1) && (n<=25)) {
System.out.println("Valid Input!");
}
else
System.out.println ("Invalid Input!!!");
if ((start>=100) && (start<=200)){
System.out.println ("Valid Input!");
}
else
System.out.println("Invalid Input!!!");
if (start%2==0) {
System.out.println ("Even Number Inputted! Next Odd Number displayed.");
}
}
It keeps telling me that int cannot be converted to boolean. I understand what it says just not sure how to rectify it.
First, prompt for the values
int minN = 1;
int maxN = 25;
int minStart = 100;
int maxStart = 200;
int start = getInput("Please enter starting value: ", minStart, maxStart);
int n = getInput("Please enter number of odd numbers to print: ", minN, maxN);
Now compute and print the results for start = 190 and n = 4
for (int i = start | 1; i <= maxStart && n-- > 0; i += 2) {
System.out.println(i);
}
prints
191
193
195
197
Explanation
First, the user is prompted for input using a method.
start - the starting point selected by the user
n - the number of values to generate also selected by the user
Then a loop is used to generate the values. This works by first, ensuring the start is odd by setting the low order bit to a 1. If the value is already odd, this has no effect. The loop begins with the first odd from start and increments by 2. The loop terminates if either i exceeds maxStart or n reaches 0.
The prompt method accepts a prompt message that is appropriate for the type of input. It also accepts a range to provide a helpful reprompt if the choice is out of range. As long as the user enters out of range values, the method will keep prompting. Otherwise, it returns the accepted value.
static Scanner input = new Scanner(System.in);
public static int getInput(String prompt, int min, int max) {
int value;
while (true) {
System.out.print(prompt);
if ((value = input.nextInt()) >= min && value <= max) {
break;
}
System.out.printf(
"Invalid entry, must be between %d and %d inclusive", min, max);
}
return value;
}
You only need one Scanner. You should perform input validation before your display loop. And your for loop syntax is incorrect, the second part should resolve to a boolean test (not an assignment) and i=start+1+=2 is just wrong. Fixing it might look something like
Scanner sc = new Scanner(System.in);
int n;
do {
System.out.println("Print how many odd numbers (n)? Enter a value between 1 and 25.");
n = sc.nextInt();
} while (n < 1 || n > 25);
int start;
do {
System.out.println("Enter starting value? Enter a value between 100 and 200.");
start = sc.nextInt();
} while (start < 100 || start > 200);
if (start % 2 != 1) {
System.out.println("Even Number Inputted! Next Odd Number displayed.");
start++;
}
for (int i = start; i < start + (2 * n); i += 2) {
System.out.println(i);
}
The problem is in the for loop condition, you must change i=n into i<=n
This is my first time posting so bare with me.
I believe that the reason you are getting int cannot be converted to boolean is because in your for loop, the second statement says i=n. This statement of the for loop needs to be a logic block.
I am a firm believer in giving resources rather than the answer, so check out this write up done by w3schools (killer resource btw) on for loops in java: https://www.w3schools.com/java/java_for_loop.asp
I believe problem is for loop at the condition part, i cannot be equal n like i=n. You can change it i<=n
I've spent all day but couldn't find a solution. Could someone please help and tell me what the error is? 75% of the code is correct, mooc says. But it fails because:
Fail: When input was: 0, output shouldn't contain: 0.
In other words, when I input 0 alone, it calculates the average of that one 0. However, the exercise calls for all non-positive numbers to be excluded from the average calculation.
This contradictory output is what I get when I enter a zero:
Give a number:
0
Cannot calculate the average
Average of the numbers: 0.0
Here is my code. I'm a beginner in Java and perhaps you guys can see something I can't. All help much appreciated
import java.util.Scanner;
public class AverageOfPositiveNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numberofinputs = 0;
double sumofinputs = 0;
double average = 0;
double negative = 0;
double positive = 0;
// For repeatedly asking for numbers
while (true) {
System.out.println("Give a number: ");
// For reading user input
int numberFromUser = Integer.valueOf(scanner.nextLine());
if (numberFromUser <= 0) {
negative = numberFromUser;
} else {
positive = numberFromUser;
}
if (positive == 0){
System.out.println("Cannot calculate the average");
}
if (numberFromUser == 0){
break;
}
if (positive == numberFromUser){
numberofinputs = numberofinputs + 1;
sumofinputs = (sumofinputs + positive);
average = (double) sumofinputs/numberofinputs;
}
}
System.out.println("Average of the numbers: " + average);
}
}
I'm new to coding. Assignment is to calculate the average of all the positive numbers input and exit when a zero is input. If no positive numbers are input display a message average not possible.
The following is what I have so far. I am stuck on the part about printing out the message "cannot calculate the average" when only a zero or negative numbers are input.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numbers = 0;
int sumOfNumbers = 0;
double averagePositive = 0;
while (true) {
System.out.println("Give a number: ");
int number = Integer.valueOf(scanner.nextLine());
if (number == 0)
break;
if (number > 0)
sumOfNumbers = number + sumOfNumbers;
if (number > 0)
numbers = numbers + 1;
if (number > 0)
averagePositive = (double)sumOfNumbers / (double)numbers;
}
System.out.println(averagePositive);
}
Try it as follows...
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Give a number: ");
int num=input.nextInt();
int tot=0; //total
int count=0; // counting the positive numbers
if(num>0){
while(num!=0){
tot+=num;
count++;
System.out.print("Give a number: ");
num=input.nextInt();
if(num<0){
System.out.print("Not possible");
return;
}
}
double avg =(double)tot/n;
System.out.print("Average: "+avg);
}else{
System.out.println("Cannot calculate the average.");
}
}
I'd probably do it like this to keep it simple. Also in general, try not to cramp code together. Most formal project demand a certain degree of styling and usually spaces between operators and braces, etc... is required. In the long run it makes the code more readable and easier to maintain.
In your code there was no need to repeat the same if test for number > 0 multiple times, they could have all been bundled together. If the program was bigger and more complex I may have named the variable names with more qualification but for a short program like this, brief names were sufficient for clarity.
continue and break are important keywords to control loop behavior and can be used to increase brevity and clarity. continue goes back to the top of the loop immediately and break exits the innermost loop immediately. Dividing a double by an int yields a double so I was able to eliminate a cast. And the += operator makes it a little easier to read the line.
Also in Java and C any if() or else clause that contains one line doesn't require braces and unless a program is nested in such a way that adding the braces anyway adds to the clarity, it is often clearer to omit the braces in that case. The if statement illustrates both ways in a single statement.
import java.util.Scanner;
public class avg
{
static int count = 0;
static double sum = 0;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("\nEnter a sequence of positive numbers (0 to calculate average):\n");
while (true) {
System.out.print("Number? ");
int n = scanner.nextInt();
if (n < 0) {
System.out.println("Negative numbers not allowed.");
continue;
} else if (n == 0)
break;
sum += (double)n;
++count;
}
System.out.println("Average of " + count + " numbers = " +
(double)(sum / count) + "\n");
System.exit(1);
}
}
Sample output:
$ java avg
Enter a sequence of positive numbers (0 to calculate average)
Number? 1
Number? 2
Number? 3
Number? 4
Number? 5
Number? -6
Negative numbers not allowed.
Number? 0
Average of 5 numbers = 3.0
I think I have to use String goAgainResponse to make there not be an infinite loop but I don't know what the code for that would look like. I'm supposed to approximate pi by adding 4 - 4/3 + 4/5 - 4/7 + 4/9 etc. adding as many of these terms together as the number that I ask the user to put in.
int term;
int counter = 1;
double piCalc=0.0;
String goAgainResponse = null;
boolean goAgain = false;
Scanner kb = new Scanner(System.in);
/* NOTE you may not declare any additional variables */
do
{
System.out.println("This program will approximate Pi based on the following series:");
System.out.println("4 - 4/3 + 4/5 - 4/7 + 4/9 - ...");
System.out.println("Enter the term number to which you would like to approximate Pi");
term = kb.nextInt();
while(term <= 9)
{
System.out.print("Please enter a number greater than 9:");
term = kb.nextInt();
}
while(term > 9)
{
term += 1;
piCalc = 4/(2 * term - 1);
System.out.print(piCalc);
}
System.out.print("Would you like to try again (yes/no)? ");
}while(goAgain);
while(term <= 9)
{
System.out.print("Please enter a number greater than 9:");
term = kb.nextInt();
}
In this you are saying term should be greater than 9. But your in your second loop condition is term>9 and you are adding values in term, thats why the second loop is infinte
while(term > 9)
{
term += 1;
piCalc = 4/(2 * term - 1);
System.out.print(piCalc);
}
changing the condition of 2nd loop would resolve your problem. OR
consider term+=1 again.
Also as per #Scary Wombat, value of boolean doagain is never set
boolean goAgain = false;
This is never set to anything else, and the loop only loops while it is true
I am very new to coding and Java. I have the following assignment: Write a program that reads a couple of positive numbers from the input and computes and prints the average, with 3 decimals precision. The input list closes with the number -1.
So I have a working program, however I have no clue how to integrate the condition 'print the average with 3 decimals precision'. Do you have any idea how to fix this? Many thanks!
See my code below:
import java.util.Scanner;
public class Parta {
public static void main(String[] args){
Scanner numInput = new Scanner(System.in);
double avg = 0.0;
double count = 0.0;
double sum = 0.0;
System.out.println("Enter a series of numbers. Enter -1 to quit.");
while (numInput.hasNextDouble())
{
double negNum = numInput.nextDouble();
if (negNum == -1)
{
System.out.println("You entered " + count + " numbers averaging " + avg + ".");
break;
}
else
{
sum += negNum;
count++;
avg = sum/count;
}
}
}
}
You just have to break out of the loop for your -1 condition.
while(1) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if(n == -1)
break;
}
Change
for(int i=0; i < numbers.length + 1= -1 ; i++)
to
for(int i=0; i < n ; i++)
The
%n
is out of place in the print statement also. I'd remove that.
To implement your -1 condition, check for a == -1 in the for loop:
if (a == -1) {break;}
The input list closes with the number -1.
I assume this means that -1 is the final number you are looking for and when read then all inputs are then completed? You just need a condition to check if the number you are looking at is -1, if it is then stop reading.
Your code does not meet your requirements.
The first requirement is that you have to calculate fractions. But you stick to int as type of your variables. As written by #nbokmans your variables should be of type double or float.
The other problem is that your code takes the first number given as the count of the numbers to follow. But you're told to use any number for calculation until input is -1. You cannot do this with a for loop, you need a while loop for this.
An the easiest way to accomplish your task is to calculate the result on the fly while getting the input:
pseudo code:
declare sum as double initially 0.0;
while(input is not -1)
sum = (sum + input) / 2;
output sum: