Hello, I am building a program that calculates the square root of a user imputed number with a given algorithum, then it does the cmath sqrt and shows the difference. When the difference is below .00001, the program breaks. Here is what I have so far, I am stuck on how to get it past just looping endlessly with the same number and putting 0 in for thedifference.
#include <iostream>
#include <cmath>
using namespace std;
using ++ increments the var by 1.0, so if you need to step through at a higher precsion you will need to change all your ++ ops to something like squareroot += .000001math += .000001thedifference += .000001
otherwise you go from 0 to 1, and nothing in between.
the output is horrendous with what you have but it at least increments correctly.
also while(thedifference != .00001) What if it never hit exactly .00001? you should use >= or <= depending on what you need it to do.
Alright, I changed the ++ to a higher precision, and took out the last while statement and changed the first while to >= so that once it hits below .00001 it stops. The output right now is just an endless stream of the square root of the number I put in, no change. I need it to take the last one it calculated, with the Algorithum ((numberGuess/previousApprox) + previousApprox)/2 and give me a more precise number. For example, with that Algorithum, the square root of 2 is 1.5, then it should take 1.5 and use it to get like 1.471 or something.
this for loop constantly resets 'thedifference'. if you need to use a different variable name for the for loop.
thedifference = newApprox - sqrt(numberGuess); sets 'thedifference equal to something, then every time the for loop is called thedifference = 0 to 1. so .9999 is reached and then you return to the while loop and this is always greater than .000001
if you want to loop through ((numberGuess/previousApprox) + previousApprox)/2 then just put that algorithm in a a single loop.
also,i believe using math::sqrt() generates a rather precise answer. the precision is outputted is determined by ios::setprecision.
I changed the increment to += .001 to get less results and this is what it is giving.
The first 5 numbers change, then it repeats. I don't know exactly what you are looking for but it appears as if it does what it does in the first 5 iterations of the first loop.
I didn't notice before, because I am not paying that much attention, but this loop just outputs the exact same thing every time..... sqrt( of any constant ) will always be the same thing.... you never change the variable numberGuess, which you shouldnt.
Yeah, it is that just without the for loop. I was confused at how the for loop worked, and the program works better without it because the numbers of times it is repeated isn't as many as you would think. Thanks a bunch for the help!!!!!
It took me a while to realize but if you remove the for loop completely the program will then output until the desired precision is reached just using the while loop.