HW


It only outputs to 2 digits! So, in the example below, it outputs 2.25. Not sure what's going on. I'm sure it's something silly...

If anyone knows and cares to share, it's much appreciated. Any other criticism or advice gratefully accepted.


Assignment specs:
Given a positive real number n, and an approximation for its square root, approx, a closer approximation to the actual square root, new-approx, can be obtained using the formula:


Using this information, write a program that prompts the user for a positive number and an initial approximation to the square root of the number, and then approximates the actual square root of the number accurate to 0.00001.

Hint: Using the initial approximation as the first value of approx, repeatedly calculate a new-approx, using the above formula, until the absolute value of the difference between the new-approx and approx is less than or equal to 0.00001. If the difference is greater than 0.00001, then calculate another new-approx, using its previous value as the value of approx.

Note: The function fabs should be used to calculate the needed absolute value. To find the absolute value of a variable x, include this code: fabs(x) Note: To use this function, you need to add #include <cmath> after the other include statement at the beginning of your code.


A sample run:

Enter n: 5
Enter first approximation: 2
The square root of 5 = 2.23607


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std; 

double calcRoot (double, double);

int main(){
	
	double x, approx, newApprox;
	
	cout << "Enter n: ";
	cin >> x;
	x = fabs(x);
	cout << "Enter first approximation: ";
	cin >> approx; 

while (approx-newApprox > 0.00001) {
	newApprox = calcRoot (x, approx);
} 
	
	cout << newApprox;
	
	return 0;
}

double calcRoot (double x, double approx){
	
	double newApprox;
	
	newApprox = ((x/approx) + approx)/2;
	
	return newApprox;
}
try

std::cout << std::setprecision(5) << newApprox << endl;
Last edited on
- You use newApprox on line 18 without initialising it.
- You never change approx, so the while loop would do the same thing repeatedly.
- You need abs(approx-newApprox) to look at the absolute difference on line 18, not assume that approx is always greater than newApprox;
- line 14 should not be necessary: you should be flagging an error if the user enters a negative number, not quietly changing his input.

Smaller, probably pedantic, issues:
- you can use abs() instead of fabs();
- please use consistent indentation (look at your while-loop);
- 0.00001 is treated as a magic number; it's also an absolute, rather than relative, error;
- your calcRoot() routine could easily be reduced to a single line (return ....)
Last edited on
Registered users can post here. Sign in or register to post.