A number minus itself gives infinite [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
In a special case I have the number 0.068404 in two variables (these change while the program is running so I don't know what is in it).
When I'm substracting by itself, it gives the infinite or precisely a number at the power -9. All booleans operations give me a wrong result.
Any ideas?

You are likely experiencing floating point rounding issues, a very common problem that has been dealt with time and time again. Consider the following program:
float a, b, c;
cin >> a;
b = a;
a = a*3;
a = a/3;
c = a - b;
cout << c << " " << (c == 0) << endl;
By all rights you should get a print out of 0 1, but when you try it here. You get:
2.48353e-09 0
This is because floating point numbers cannot represent every base 10 number, so rounding errors make straight comparisons a bad idea. You should always use an epsilon, ie:
abs(a - b) < eps
where eps is something like 1e-6.
Here you can find many more examples.

Related

Recursive function, geometric progression [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I've just started learning C++ and I came across a simple problem but couldn't solve. Help me please,
In geometric progression, b1=2, r=3.
Create recursive function that outputs initial n sequences of progression. n should be input.
Assuming b1 is the initial number and r is the multiplier (ratio?), that would give 2, 6, 18, 54, ....
The pseudo-code for such a beast would be:
def geometric (limit, current, multiplier):
if limit <= 0: return
print(current)
geometric(limit - 1, current * multiplier, multiplier)
def main():
b1 = 2
r = 3
n = input("How many terms? ")
geometric(n, b1, r)
The reason it's pseudo-code is that I tend to prefer for educational questions since people learn a lot more by converting it rather than just being given an answer.
So, in terms of how the recursive function works, you pass it the number of terms remaining along with the current term and the multiplier.
Provided it hasn't reached its base case (number of terms remaining is zero), it prints the current term then recursively calls itself, adjusting the arguments so as to approach the base case.
Once it has reached the base case, it will return (from all recursive levels).
Turning that into C++ is an exercise I'll leave for the reader, but I can provide something similar so you will see the approach taken.
Let's say you wanted to sum all the numbers between 1 and a given number. It has the same features as any recursive solution, including the one posed in your question:
an operation that can be defined in terms of a simpler operation; and
the base case.
In C++, a complete program to do that would be something like:
#include <iostream>
void recurse(int number, int sum) {
// Base case for printing and returning.
if (number <= 0) {
std::cout << "Sum is " << sum << '\n';
return;
}
// Recurse to next level.
recurse(number - 1, sum + number);
}
int main() {
int myNum;
std::cout << "Enter your number: ";
std::cin >> myNum;
recurse(myNum, 0);
}
Some sample runs:
Enter your number: 3
Sum is 6
Enter your number: 4
Sum is 10
Enter your number: 5
Sum is 15
Enter your number: 6
Sum is 21
Enter your number: 100
Sum is 5050
The explanatory text on your specific question, along with the C++ code showing how to do it for a different question, should hopefully be enough for you to work it out.

given a number and its root value, finding nth root of a number [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
can someone please explain this below-mentioned code?
double b=0.0;
double a=0.001;
double r=0;
printf("Type the number and root value \n");
scanf("%lf %lf",&b,&r);
while(pow(a,r)<(b + 0.05)){
a += 0.001;
}
printf("The %f root of %f is = %f\n",r,b,a);
return 0;
for example, if the number is 32 and the root value is 5
output: the 5 root of 32 is = 2
It's a simple trial and error method where you take a random small number as a base and increment it to a power(which is r in your case) until it becomes greater than or equal to your desired number.
Here, your random number is a, which you increment every time until pow becomes greater than b.

Calculation of value of Pi up to 'n' decimal places [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I was trying to make a C++ program to calculate value of Pi up to 'n' decimal places using the Leibniz formula.
The number 'n' would be entered by the user.
I was successful in creating the Leibniz formula but I am having trouble with the latter part i.e value precise up to 'n' places.
The trouble :-
As more and more terms will continue to add to it, it's digits will keep on changing so how to tell if a particular digit has stopped changing despite the addition of more terms.
The code written so far :-
#include<iostream>
using namespace std;
int main()
{
float s=0;
int w=-1;
for(float i=1;;i=i+2)
{
w=w*(-1);
s=s+w*(1/i);
cout<<s<<endl;
}
return 0;
}
It would be great if things would be kept simple since I am just a beginner at C++.
Thank you very much :)
Since you want to compute Pi up to arbitrary nth digit, you want a library for working with big float numbers; see
C++ library for big float numbers
the real trouble is that Leibniz formula is not useful in the context. The actual precision achieved can be estimated as the last term in the formula
Pi / 4 = 1/1 - 1/3 + 1/5 - 1/7 + ... + (-1)**(n + 1) * 1 / (2 * n - 1) + ...
If, for intance, you want Pi up to 100th digit it means that the residual (and the last term) should be less than 1e-100:
1 / (2 * n - 1) < 1e-100
2 * n - 1 > 1e100
n > 5e99
And as you can see 5e99 loops is by far too much for the modern (super-)computers

Calculate the payment [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
double total,grandtotal;
double amount, change=0;
total=day* price* noRoom;
grandtotal=total*1.16;
cout<<"\t\tPlease enter your amount:RM";
cin>>amount;
while (amount < grandtotal)
{
cout << "\t\tPlease enter a valid amount:RM";
cin >> amount;
}
change=amount-grandtotal;
if (amount > grandtotal)
{
cout<<"\t\tYour change is: "<<change <<endl;
cout<<"\t\tThank You, Have a nice day! \n";
cout<<"\t\t Please come again \n";
}
else if( amount == grandtotal) //why this statement can't run if my amount is also equal to the grandtotal???
{
cout<<"\t\tThank You, Have a nice day! \n";
cout<<"\t \tPlease come again \n";
}
Your else if might be executed but most likely it won't happen, because double values precision is relatively high so there will be difference.
If you set the precision smaller for example that should work.
eg 2.11 == 2.11 rather than 2.15151523 == 2.15151524
This question might help you doing so.
My observation is that you are using floating point values for financial transactions. This is not a good idea. The representation of floating point numbers can be approximate for certain floating point values. It would be much better to use (long) integers to represent the pence/cents, and then represent the larger denomination in the output function.
That way your test will work.
In some contexts you may want to compare floats then use a very small constant floating point value perhaps called epsilon and have the test.
if (fabs(amount - grandtotal) < epsilon)
{
cout<<"\t\tThank You, Have a nice day! \n";
cout<<"\t \tPlease come again \n";
}

Translation of number into strings [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I would like to know whether there is a way in which we can print the number alphabetically i.e
123 should be printed as one two three.
The only condition is that we should not reverse the number and we should not use array.
I only know these two ways:
"Reverse the number", that is, taking the last digit and cutting it off. For each cut-off digit, one can use an array to look up the correct string.
using switch and a lot of cases
Any ideas?
for hundreds place:
int hundreds = my_num / 100 //Needs "/", NOT "%"
if(hundreds == 0)
cout << "zero";
else if(hundreds == 1)
cout << "one";
//repeat for 2-9
This process could be tweaked to do the other digits as well. It is also worth mentioning that the if/else block a) could be done with a switch/case if preferred, and b) could pretty easily be made into a separate function to avoid having to repeat the block of code over and over, I just wrote out as much as I did for clarity's sake. Note that this assumes the number you're "translating" is an integer. With integers the "/" operator will return the full quotient WITHOUT the remainder, e.g. 123 / 100 = 1, not 1.23
Not necessarily the easiest route, but you can make a function, say DigitToWord which will take a digit 0, 1, 2, ...etc to its word with a switch statement. Then I recommend using a for loop over the number, continuously dividing by 10 and taking the mod for the loop:
int num; //my number i want to print
int div = pow(10, (int)log10(num)); //find the largest power of 10 smaller than num
while(num > 0) {
int remainder = num%div;
int digit = num/div;
DigitToWord();
num = remainder;
}