I'm trying to learn C++ and there is a problem I am trying to work out. Basically I need to calculate the square root of a number. I think I'm on the right track, but when I run the code nothing happens after I input a number.
int n;
double r, intGuess, guess, ratio;
// user input
cout << "Enter number: ";
cin >> n;
intGuess = n;
guess = n / 2;
ratio = intGuess / guess;
while (ratio >= 1.01 || ratio <= 0.99)
{
r = n / guess;
guess = (guess + r) / 2;
}
cout << endl;
cout << "The square root of " << n << " is " << guess << endl;
Your loop seems to be infinite because you never update ratio inside it... then if the condition is true once, it is true forever...
It should be something like:
ratio = intGuess / guess;
while (ratio >= 1.01 || ratio <= 0.99)
{
intGuess = guess; // Save the previous value of guess
r = n / guess;
guess = (guess + r) / 2;
ratio = intGuess / guess; // Update ratio here with the previous and the
// actual value of guess
}
Also:
until guess is within 1% of the previous guess
You should save the previous guess and use this one for your ratio, not the original one.
Live example of this algorithm. I added two lines in the loop.
You are supposed to be comparing the previous guess to the current one. That's not what you are doing.
Example: Suppose you input 4. The first guess is going to be 2, which is the exact value. Every successive guess will also be 2. Even if you update the ratio as IntGuess/guess inside the loop, it's going to be 2. Always.
Fix your code so you are comparing the previous guess and the current one and all will be good.
Related
I'm having trouble giving the user an option to loop a loop. This program works fine
#include <iostream>
using namespace std;
int main()
{
// goal is to calculate the sum of the first 10 terms of Leibniz's Series....
// calculated by 1 - 1/3 + 1/5 - 1/7 + 1/9 ..... - 1/19
int termNumber; // keeps track of term numbers
int numberOfTerms = 0;
cout << "Enter number of Terms";
cin >> numberOfTerms;
double sum = 0.0;
int sign = +1;
for (termNumber = 1; termNumber <= numberOfTerms; termNumber++)
{
sum += ( sign / (2.0 * termNumber - 1));
sign *= -1;
}
cout << "\n\n The sum is " << ( 4 * sum) << "\n\n";
} // end body of loop
I need to give the user an option to repeat the program if he would like so I thought I could put it in a do-while loop, but when I do that it only loops "enter number of terms" any way I try to format it. This is the best I have at the moment.
#include <iostream>
using namespace std;
int main()
{
// goal is to calculate the sum of the first 10 terms of Leibniz's Series....
// calculated by 1 - 1/3 + 1/5 - 1/7 + 1/9 ..... - 1/19
cout << "\nGiven a positive integer specifying some number of terms, this program\n approximates "
"pi using Leibniz' Formula and the given number of terms.\n\n" ;
cout << "Leibniz' formula is 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ... = Pi / 4.\n\n";
char yes = 0;
double sum = 0.0;
do {
int termNumber; // keeps track of term numbers
int numberOfTerms = 0;
int sign = +1;
cout << "enter number of terms.\n";
cin >> numberOfTerms;
for (termNumber = 1; termNumber <= numberOfTerms; termNumber++)
{
sum += (sign / (2.0 * termNumber - 1));
sign *= -1;
}
}
while (yes = 1);
cout << "\n\n The sum is " << (4 * sum) << "\n\n";
cout << "would you like to go again? " << yes;
} // end body of loop
I would like to give them the option to try a different amount using term numbers where y/Y and n/N work.
Thanks for any help I may get.
You need a cin to set yes and your cout lines are in the wrong place. They need to be inside of your do while loop. And an == in your while
do {
int termNumber; // keeps track of term numbers
int numberOfTerms = 0;
int sign = +1;
cout << "enter number of terms.\n";
cin >> numberOfTerms;
for (termNumber = 1; termNumber <= numberOfTerms; termNumber++)
{
sum += (sign / (2.0 * termNumber - 1));
sign *= -1;
}
cout << "\n\n The sum is " << (4 * sum) << "\n\n";
cout << "would you like to go again? " << yes;
cin >> yes
}
while (yes == 1);
try that
Just my two cents but maybe you can combine both of your ideas and use functions. Put the code you have in the do part above into a function with a parameter of number of terms. Also use your for loop in the body of this function. Then on the outside of your for loop call another function that asks the user if they would like to continue and also ask a new number for the "terms" and pass that back into the first function if the user supplies a 'y' or 'Y' else if a 'n' or 'N' you can just stop the program
Have you learned to use
continue;
in a for loop? I think this fits your description, basically what
continue;
does is it returns to the beginning of the for-loop in this case in a certain scenario.
The problem with the do while loop is that the variable used in the while() statement must have been defined outside of the loop body, even though syntactically is belongs to the loop. This can be avoided when using a for loop instead, which allows the definition of such variables within the for statement. Here is an example.
inline double leibniz (int n) noexcept // function for Leibniz sum
{
double result=0;
for(int k=1,sign=1; n; --n,++++k,sign=-sign)
result += double(sign)/double(k);
return result;
};
int main()
{
// no loose variables defined outside loop
for(bool again=true; again; ) { // control variable only lives withing loop body
int n; // number of terms, only needed within loop body
std::cout<<"number of terms = ";
std::cin >> n;
std::cout<<"result = "<<leibniz(n)<<'\n'
<<"try again? (1/0)";
std::cin >>again;
}
}
Thanks everyone for the help.
I didn't know the continue; yet, but I learned about it.
The major problem was my cin and cout were not in the right spot like stated before. Redid the last line to while (yes == 'Y' || yes == 'y'); and now all works perfectly.
You guys are great!
I have thoroughly searched for this topic all over the internet, and the threads are either dead, or use a different method than what is described in my book.
For example, http://www.geeksforgeeks.org/square-root-of-a-perfect-square/ . This doesn't work for me because my algorithm needs to loop until it reaches 1% of the last "guess".
Here is the question from the text.
The Babylonian algorithm to compute the square root of a number n is as follows:
Make a guess at the number (you can pick n/2 as your initial guess).
Compute r = n / guess
Set guess = (guess + r) / 2
Go back to step 2 for as many iterations as necessary. The more that steps 2 and 3 are repeated, the closer guess will become to the
square root of n.
Write a program that inputs an integer for n, iterates through the
Babylonian algorithm until guess is within 1% of the previous guess,
and outputs the answer as a double.
I have written the following code:
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
int n;
double r, guess(4), lastGuess;
cout << "Enter a number to find the square root of: ";
cin >> n;
do
{
r = n / guess;
lastGuess = guess;
guess = ( guess + r ) / 2;
// cout <<"Guess: " << guess << endl;
// cout <<"Last Guess: " << lastGuess << endl;
cout << "Guess : " << guess << endl;
cout << "Last Guess 1% = " << lastGuess + ( lastGuess * 0.01 ) << endl;
cout << "r = " << r << endl;
} while( guess >= lastGuess * 0.01 );
cout << r;
return 0;
}
The program computes the right answer for r, but the loop doesn't terminate despite guess being greater than 1% added to lastGuess.
This program produces the following output when inputting 144 as n.
....
r = 12
Guess : 12
Last Guess 1% = 12.12
r = 12
Guess : 12
Last Guess 1% = 12.12
r = 12
Guess : 12
Last Guess 1% = 12.12
r = 12
Guess : 12
Last Guess 1% = 12.12
....
The root (r) is correct (12). The guess is LESS than lastGuess (12 < 12.12), which should return a false to the condition, correct?. Why is the loop not ending?
If you want to add 1% you need to multiply by 1.01, not 0.01.
while( guess >= lastGuess * 1.01 );
By the way, this iterates while guess is growing by more than 1%. You should also allow for the opposite, that it may have shrunk by more than 1%. The approximation could approach the answer from either direction. (It will approach positive roots from the right and negative roots from the left.)
While printing your lastGuess you are using
lastGuess + ( lastGuess * 0.01 )
But while checking loop condition you are using
lastGuess*0.01
So in loop condition use the same equation which you are using for printing lastGuess value.
To properly exit the loop, use something similar to this.
void f(int N)
{
double x = N / 4;
double prev = 0.0f;
while(1)
{
x = 0.5 * (x + N / x);
if (prev == x)
break;
prev = x;
printf("val: %f\n", x);
}
printf("SQRT(%d) = %f\n", N, x);
}
I had the same problem in my book. This is what I wrote and it works perfect.
#include <iostream>
using namespace std;
int main()
{
double guess, root, previousGuess;
int number;
cout << "Enter a number to find the Babylonian square root.\n";
cin >> number;
cout << "You want to find the square root of " << number << ".\n";
cout << "Enter a guess for the square root.\n";
cin >> guess;
do
{
root = number / guess;
previousGuess = guess;
guess = (guess + root ) / 2;
} while(guess < 0.99*previousGuess || guess > 1.01*previousGuess);
cout << "The answer is " << guess << ".\n";
return 0;
}
//Purpose: To calculate the price to pay an author
//Programmer: Brandon C Ballard
//Last Updated: 2/20/2014
#include <iostream>
#include <cstdlib>
using namespace std;
//function prototype
float TotalPay(int numWords, char Level);
int main()
{
float TotalPay;
int numWords;
char Level;
int amtToPay;
cout << "Please enter number of words: ";
cin >> numWords;
cout << endl;
cout << "Please enter a Level, A,B, or C: ";
cin >> Level; cout << endl << endl;
//calculate price per word
if (numWords < 7500)
amtToPay = numWords * .08;
else if (numWords >= 7500 && numWords < 8000)
amtToPay = 600;
else if (numWords >= 8000 && numWords < 17500)
amtToPay = numWords * .075;
else if (numWords >= 17500 && numWords < 19000)
amtToPay = 1313;
else
amtToPay = numWords *.07;
//calculate the Level of the author
if (Level == 'C' or Level == 'c')
Level = 1;
else if (Level == 'B' or Level == 'b')
Level = 1.25;
else if (Level == 'A' or Level == 'a')
Level = 1.75;
TotalPay = amtToPay * Level;
cout << "Length of Story (words): "; cout << numWords; cout << endl << endl;
cout << "Amount Due Author: "; cout << "$"; cout << TotalPay; cout << endl << endl << endl;
system("PAUSE");
return 0;
}//end main function
My instructor wants me to write a program that can calculate the amount of money to pay an author who is submitting an article to a magazine. The amount of money to pay the author is based off of how many words are in the article. It works like this...
-if length (in words) is less than 7,500: the author gets paid $0.08 per word.
-if length is 7,500 to 8,000: the author gets paid a fixed $600.
-if length is 8,000 to 17,500: the author gets paid $0.075 per word.
-if length is 17,500 to 19,000: the author gets paid a fixed $1313.
-if length is greater than 19,000: the author gets paid $0.08 per word.
Also: There are three different "Levels" of authors (A,B, and C). A "C" Level author (new author) would get paid based on the information above. A "B" Level author (established writer) would get paid 1.25 times the amount of a Level C author. An "A" Level author (rockstar) would get paid 1.75 times the amount of a Level C author.
The Math: Basically, I wrote the program so that it first calculates the amount to pay the author (amtToPay). Then, it calculates what the (Level) is equal to. Then the (TotalPay) is the (amtToPay) multiplied by the (Level).
My Problem: Everything works great except for the part where it //calculates the Level of the author. For example, if I were to input the author as an "A" Level, he should get paid 1.75 times that of a Level C author. So, it should multiply the (amtToPay) by 1.75, except what is actually doing is multiplying it by "1" and is ignoring the ".75".
I am new to programming and I understand that there are probably many other ways to write this. But please try and help me the best that you can. Thank you.
Level is an integer type so when you assign the floating point numbers to it, the fractional parts are dropped.
Try defining double rateLevel and then
if (Level == 'C' or Level == 'c')
rateLevel = 1;
else if (Level == 'B' or Level == 'b')
rateLevel = 1.25;
else if (Level == 'A' or Level == 'a')
rateLevel = 1.75;
TotalPay = amtToPay * rateLevel;
The proper way to do this is to not use floating point types at all, except maybe for printouts. The way to accomplish this is to scale everything by a power of ten that will remove all fractional components from your values. In your code the least significant digit is in the thousands place (0.075). This means that you need to multiply all your values by 1000. This is called your scale factor. Then you can do your math using only integral types, int, long, int64_t, etc. At the end of your calculations you can split the results into whole number and fractional components.
Like this:
int TotalPayDollars = TotalPay/1000;
int TotalPayMilliDollars = TotalPay - 1000*TotalPayDollars;
int TotalPayCents = (int)((double)TotalPayMilliDollars/10 + 0.5);
The first line is all integer math so the dividing by 1000 discards any fractional parts.
The second line finds the difference between your original value and the truncated value. We multiply TotalPayDollars by 1000 to bring it into the same units as TotalPay again.
In the last line the + 0.5 works to round up to the nearest cent.
NOTE: when choosing a scale factor it is very important to make sure that you don't overflow your integer type. A 32 bit signed integer can only hold numbers up to 2^31-1 (2,147,483,647). If any of your calculations will go higher than that value then you should use a 64 bit integer type.
Level is type char which is integral, you should create a new variable specifically to hold the amount boosted by level:
double level_boost;
//logic
Totalpay = amtToPay * level_boost;
PS: in your logic, you do not have to use &&:
if (numWords < 7500)
amtToPay = numWords * .08;
else if (numWords < 8000)
//if the numwords is less than 7500 will be handled by first if
amtToPay = 600;
I am trying to make a simple guess my number game in c++ but the computer need to guess my number. But the problem is that I am stuck in this infinite loop. I am just a beginner so it's a really basic program.
This is my code:
int secretNumber = rand() %100 + 1; // random number between 1-100
int tries=0;
int input;
cout <<"typ your number\n";
cin >> input;
do
{
cout <<secretNumber <<endl;
++tries;
if (secretNumber > input)
{
cout <<"To high i guess?\n";
}
else if (secretNumber < input)
{
cout <<"To low I guess?\n";
}
else
{
cout <<"Yes, i got it in " <<tries <<" tries!";
}
}while (input != secretNumber);
return 0;
}
place cin >> input into loop body
I think you should move the random number generation inside the loop.
The value of the variable input is never changed in the loop, so the terminating condition input != secretNumber is never met.
You should take the input inside the loop. So write cin >> input at the beginning of the loop.
Edit:
If the computer should guess, then still the value of input needs to be changed in the loop, which is not present in your code. The loop runs with the same value in input every time.
To make you computer make a guess, you should follow some scheme. The computer may draw the numbers at random - which you can get through moving secretNumber = rand()%100 + 1 inside the loop. But this approach may not perform good, the loop may still run for a very long time. This is shown in #Kaii's answer.
A more efficient approach is the Binary Search. In this case you should keep track of the guesses the computer makes. Keep two variables high and low which should store the guesses higher and lower than input respectively. Whenever a guess in higher than the number, store it in high, and store any guess lower than input in low. Then the computer should try its new guess between high and low. A random guess should be secretNumber = low + rand() % (high - low). In worst case it will take as much as 100 iterations. For the best results, each guess should be (high + low) / 2. According to the conditions, one of high and low will be updated in each iteration. This approach will ensure that the computer will guess the correct number within 7 guesses.
In your code it should be like this:
int secretNumber = rand() % 100 + 1; // random number between 1-100
int tries=0;
int input;
int low = 1, high = 100;
cout <<"typ your number\n";
cin >> input;
do
{
secretNumber = (high + low) / 2;
cout << secretNumber <<endl;
++tries;
if (secretNumber > input)
{
cout << "Too high I guess?\n";
high = secretNumber;
}
else if (secretNumber < input)
{
cout << "Too low I guess?\n";
low = secretNumber;
}
else
{
cout << "Yes, i got it in " << tries << " tries!";
}
} while (input != secretNumber);
return 0;
the computer is only guessing (by random) once when the program starts, but should guess each time the loop is iterated. you should move the random number generation inside the loop:
int secretNumber = 0;
int tries=0;
int input;
cout <<"typ your number\n";
cin >> input;
do
{
/* the fix is here */
secretNumber = rand() %100 + 1; // random number between 1-100
cout <<secretNumber <<endl;
++tries;
if (secretNumber > input)
{
cout <<"To high i guess?\n";
}
else if (secretNumber < input)
{
cout <<"To low I guess?\n";
}
else
{
cout <<"Yes, i got it in " <<tries <<" tries!";
}
}while (input != secretNumber);
return 0;
You have to do the input within the loop. Right now you prompt for a value BEFORE you start looping, then never ask the user for another number. If the guess can't be changed, the loop can never exit.
changing to
do {
cin >> input;
will solve the infinite loop.
infinite loop in your code because the argument for while always true until you get the true number.
you need to add another argument. example you want set maximal tries to 5 times. then it will be like this
do{
//do your stuff here
}while((input != secretNumber)&&(tries<=5))
when you input wrong number for 5 times, the application will finish
I need some help revising this. It keeps only displaying 0s as the temp. Thank you.
// A program to determine whether the input number is a perfect number
// A perfect number is defined by the sum of all its positive divisors excluding itself
// 28: 1+2+3+7+14 = 28.
int perfect, limit, divisor;
cout << "Please enter a positive integer in order to define whether it is a perfect integer or not: " ;
cin >> perfect;
cout << endl;
int temp = 0;
int prevtemp = 0;
limit = 1;
divisor = 1;
while (limit < perfect)
{
if ((perfect % divisor) == 0)
{
divisor = prevtemp;
temp = prevtemp + temp;
}
limit++;
divisor++;
}
if (perfect == temp)
cout << "Your number is a perfect number!" << endl;
else
cout << "Your number is not a perfect number" << endl;
return 0;
You are never setting prevtemp to anything other than 0, so adding it to temp does nothing.
I believe you meant to say
if ((perfect % divisor) == 0)
temp += divisor; // not "divisor = prevtemp;"
The line "temp = prevtemp + temp" should also be removed with this solution; there is no longer any need for the prevtemp variable.
Also, there is no need to keep separate limit and divisor variables, since they are always the same. Just remove limit and change the loop condition to use divisor.
Also, as Mark Byers pointed out, the loop would be simpler to understand if you refactored it into a for loop rather than a while.
It seems like you are making it too complicated. Here's how you could do it:
int total = 0;
for (int i = 1; i < perfect; ++i)
{
if (perfect % i == 0)
total += i;
}
if (perfect == total)
cout << "Your number is a perfect number!" << endl;
else
cout << "Your number is not a perfect number" << endl;
Note that the running total is kept in a variable called total (you called this variable temp) and it is only increased when the number is an exact divisor.
I'm not sure, but I'd guess that in the code:
if ((perfect % divisor) == 0)
divisor = prevtemp;
you intended this to be prevtemp=divisor instead. That fixes an obvious problem, but still leaves quite a bit that doesn't look like it's doing that you probably intended. For example, I can't quite figure out what limit is intended to accomplish -- you initialize it and increment it, but as far as I can see, you never use its value (well, I guess you use it, but its value is always the same as divisor's so I'm not sure why you think you need both, or how limit makes any sense as its name).
Edit: It would make sense to have a limit. In particular, factors always come in pairs: one that's less than or equal to the square root of the number, and one that matches the first that's always greater than or equal to the square root of the number. As such, you don't need to scan all the way up to the number itself looking for factors -- you can set the square root of the number as the limit, and scan only up to that point. For each factor you find up to that point, the matching factor will be perfect/divisor. Since you've already gotten one working example, I guess I might as well just hope this isn't homework, and post an example as well:
bool is_perfect(int number) {
int limit = sqrt((double)number);
int sum = 1;
for (int i=2; i<=limit; i++)
if (number % i == 0)
sum += i + number/i;
return sum == number;
}
You are never assigning anything to prevtemp after initializing it to 0, so there is nothing to add to temp on the line that reads temp = prevtemp + temp.
#include<iostream>
#include<iomanip>
using namespace std;
int main(){
int n,i=1,sum=0;
cout<<"Enter a number: ";
cin >> n;
while(i<n){
if(n%i==0)
sum=sum+i;
i++;
}
if(sum==n)
cout << i << " is a perfect number";
else
cout << i << " is not a perfect number";
system("pause");
return 0;
}