Algorithm for the cube root Find in C++ - c++

Iam Beginner in programming and i have a question.
how make algorithm for cube root finding in C++ without using functions like pow().
The user enters the number and the number of decimal places.
My code:
My do while isn't working
double number;
cout << "Enter number = ";
cin >> number;
int x;
int y = number / 3.;
int i;
cout << "Enter i = ";
cin >> i;
do {
x = y;
y = (2. * x + number / (x * x)) / 3.;
} while (abs(x - y) >= i);

Your algorithm is nearly fine. You just need to change your variables to float/double. Here is the edited code :
#include <iomanip>
#include <iostream>
#include <limits>
using namespace std;
int main() {
double number;
cout << "Enter number = ";
cin >> number;
double x;
double y = number / 3.;
double i;
cout << "Enter i = ";
cin >> i;
do {
x = y;
y = (2. * x + number / (x * x)) / 3.;
} while (abs(x - y) >= numeric_limits<double>::epsilon());
cout << fixed << setprecision(i) << y;
}
Sample Run :
Enter number = 10
Enter i = 2
2.15
A little add up :
As pointed out by chux - Reinstate Monica, abs(x - y) >= numeric_limits<double>::epsilon() is not a good condition to check equality. You can go through this thread for more knowledge : What is the most effective way for float and double comparison?
Another one : Why is “using namespace std;” considered bad practice?

Related

Functions arcsin and arccos are not working properly

I need to write the code for solving a simple equation, which should contain arcsin and arccos.
Formulas
F = cos^2(p(x)) + sin^2(p(y) + p(z)
p(k) = arccos(a * k) + arcsin(k)
Here is the code I wrote for solving it, but it gives -nan Ind as output. However, when I fix acos and asin to just cos and sin, everything works.
Expected input:
x = 1.20
y = 3.05
z = 2.00
Code
#include <iostream>
#include <math.h>
using namespace std;
const double a = 0.01;
double p(double k) {
double p1;
p1 = acos(a * k) + asin(k);
return (p1);
}
int main() {
double x;
double y;
double z;
double F;
cout << "x = "; cin >> x;
cout << "y = "; cin >> y;
cout << "z = "; cin >> z;
F = pow(cos(p(x)), 2) + pow(sin(p(y)), 2) + p(z);
cout << "F = " << F << endl;
return 0;
}
The OUTPUT range of SIN and COS is [-1, +1]. That means the INPUT range of ARC (inverse) sin is [-1, +1]. You are trying to do asin(1.2), which probably yields NaN.

I want to find the sum of range between two numbers?

#include <iostream>
#include <algorithm>
using namespace std;
void sumrange(int x, int y) {
int sum;
cout << "Enter the first number: ";
cin >> x;
cout << "Enter the second number: ";
cin >> y ;
int bnum = max(x,y);
int snum = min(x,y);
int i = snum;
while (i < bnum) { sum =+ i; i++; }
cout << sum;
}
int main() {
int x, y;
sumrange(x,y);
return 0;
}
I can't get the right answer from my input I tried 1 and 4 and the answer was 3 but it supposes to be 1+2+3+4 which is 10.
Couple of observations:
don't use using namespace std; it is a bad practice and might lead to name conflicts
variable int sum needs to be explicitly initialized before use
sum =+ i should be sum += i
you need to use <= if you want to include the upper bound
take a look at the arithmetic sequence
sumrange function doesn't need parameters, sice they are passed by value int x, y; from your main are not used at all
Following code should do what you want:
#include <iostream>
#include <algorithm>
void sumrange()
{
int x;
int y;
int sum = 0;
std::cout << "Enter the first number: ";
std::cin >> x;
std::cout << "Enter the second number: ";
std::cin >> y ;
int bnum = std::max(x,y);
int snum = std::min(x,y);
int i = snum;
while (i <= bnum) { sum += i; i++; }
std::cout << sum;
}
int main() {
sumrange();
return 0;
}
You have inverted the += sign to =+
It should be sum += i .
sum = +i assigns the number to itself
Edit: you should also initialize sum, stated in the comment
There are 3 problems with your given code snippet.
Problem 1: =+ should be += in the statement:
sum =+ i; //=+ should be +=
Problem 2: The variable sum is uninitialized and so it has a garbage value. Using that garbage value leads to undefined behavior.
Problem 3: Should use <= instead of < in the statement
while (i < bnum) //should be i<=bnum
So the modified(corrected) program looks like below:
#include <iostream>
#include <algorithm>
void sumrange(int x, int y) {
int sum=0;///INITIALIZE sum
std::cout << "Enter the first number: ";
std::cin >> x;
std::cout << "Enter the second number: ";
std::cin >> y ;
int bnum = std::max(x,y);
int snum = std::min(x,y);
int i = snum;
while (i <= bnum) //USED <=
{
sum += i; //USED +=
i++;
}
std::cout << sum;
}
int main() {
int x, y;
sumrange(x,y);
return 0;
}
Alternative solution
Note that you can find the sum without using a loop as shown below:
#include <iostream>
#include <algorithm>
void sumrange(int x, int y) {
int sum=0;//initialize sum
std::cout << "Enter the first number: ";
std::cin >> x;
std::cout << "Enter the second number: ";
std::cin >> y ;
sum = (std::abs(x - y) + 1) * (x + y) / 2; //ADDED THIS
std::cout << sum;
}
int main() {
int x, y;
sumrange(x,y);
return 0;
}
A C++20 solution :
#include <algorithm>
#include <iostream>
#include <numeric>
#include <ranges>
int main()
{
int a{ 0 };
int b{ 0 };
std::cout << "Enter the first number: ";
std::cin >> a;
std::cout << "Enter the second number: ";
std::cin >> b;
auto lower_bound = std::min(a, b);
auto upper_bound = std::max(a, b) + 1; // iota view is exclusive so add 1
auto view = std::ranges::iota_view{ lower_bound , upper_bound };
auto sum = std::accumulate(view.begin(), view.end(), 0);
std::cout << "sum = " << sum << "\n";
return 0;
}
constexpr auto sumrange(const int x, const int y) noexcept {
auto sum = 0;
if (x < y) for (auto i = x; i <= y; ++i) sum += i; else
if (y < x) for (auto i = y; i <= x; ++i) sum += i;
return sum;
}
int main() {
constexpr auto x = 1;
constexpr auto y = 3;
constexpr auto r = sumrange(x, y); // 1 + 2 + 3
std::cout << r << '\n'; // 6
}
Values of the function arguments are not used in this call
int x, y;
sumrange(x,y);
So such a call does not make a sense.
You need in main to ask the user to enter a range of numbers and pass the range to the function.
The task of the function is to return the calculated sum for the specified range in main.
Within the function sumrange the variable sum is not initialized.
int sum;
You need to initialize it to 0.
In this while loop
while (i < bnum) { sum =+ i; i++; }
^^
there is a typo. Instead of the compound assignment operator += you are using the assignment operator = and the unary + operator
Moreover as it follows from your comment you need also to add the value of bnum to the sum.
So the loop should look at least like
while (i <= bnum) { sum += i; i++; }
Pay attention to that in general an overflow can occur. So it is better to declare the variable sum as having the type long long int.
The function and the program can look the following way
#include <iostream>
#include <utility>
#include <algorithm>
long long int range_sum( int x, int y )
{
long long int sum = 0;
auto [first, last] = std::minmax( { x, y } );
do
{
sum += first;
} while (first++ != last);
return sum;
}
int main()
{
int x = 0, y = 0;
std::cout << "Enter the first number: ";
std::cin >> x;
std::cout << "Enter the second number: ";
std::cin >> y;
std::tie( x, y ) = std::minmax( { x, y } );
std::cout << "The sum of numbers in the range ["
<< x << ", " << y << "] is equal to "
<< range_sum( x, y )
<< '\n';
}
The program output might look like
Enter the first number: 1
Enter the second number: 10
The sum of numbers in the range [1, 10] is equal to 55

Count how many times number entered until the first symmetry number is entered

I wrote the following code but only works when the first number is symmetry:
symmetry is like this number: 4554 (reading from both ends is the same number)
My question is why the break only works for the first number? It happens when I run it.
#include <iostream>
using namespace std;
int main()
{
int n=0, z=0, r=0, x=0, m;
for (;;) {
cout << "Enter number: ";
cin >> x;
m = x;
while(x!=0) {
r = x % 10;
z = z * 10 + r;
x = x / 10;
}
if(m==z)
break;
else
n++;
}
cout << n;
return 0;
}
Move int z=0, r=0; inside for loop.
Why not using this code to know if the number is symmetry?
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
int x;
for (;;) {
cout << "Enter number: ";
cin >> x;
m = x;
std::stringstream str;
str << x;
std::string number = str.str();
if ( number == std::string( number.rbegin(), number.rend() )
break;
else
n++;
}
cout << n;
return 0;
}
Simpler, leads to the same result and is definitely more error prone ;-)
It would have been much easier to reason if you have written like this:
#include <iostream>
bool isPalindrome(int x)
{
int y = x;
int z;
while (x) {
z = z * 10 + x % 10;
x /= 10;
}
return y == z;
}
int main()
{
int n = 0;
int x;
for (;;) {
std::cout << "Enter number: ";
std::cin >> x;
if (isPalindrome(x))
break;
else
++n;
}
std::out << "Number of non-palindromes: " << n << std::endl;
return 0;
}
functions with meaningful names always helpful!

Counting digits using while loop

I was recently making a program which needed to check the number of digits in a number inputted by the user. As a result I made the following code:
int x;
cout << "Enter a number: ";
cin >> x;
x /= 10;
while(x > 0)
{
count++;
x = x/10;
}
From what I can tell (even with my limited experience) is that it seems crude and rather unelegant.
Does anyone have an idea on how to improve this code (while not using an inbuilt c++ function)?
In your particular example you could read the number as a string and count the number of characters.
But for the general case, you can do it your way or you can use a base-10 logarithm.
Here is the logarithm example:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double n;
cout << "Enter a number: ";
cin >> n;
cout << "Log 10 is " << log10(n) << endl;
cout << "Digits are " << ceil(log10(fabs(n)+1)) << endl;
return 0;
}
int count = (x == 0) ? 1 : (int)(std::log10(std::abs((double)(x)))))) + 1;
You could read the user input as a string, and then count the characters? (After sanitising and trimming, etc.)
Alternatively, you could get a library to do the hard work for you; convert the value back to a string, and then count the characters:
cin >> x;
stringstream ss;
ss << x;
int len = ss.str().length();
If x is an integer, and by "built in function" you aren't excluding logarithms, then you could do
double doub_x=double(x);
double digits=log(abs(doub_x))/log(10.0);
int digits= int(num_digits);
Given a very pipelined cpu with conditional moves, this example may be quicker:
if (x > 100000000) { x /= 100000000; count += 8; }
if (x > 10000) { x /= 10000; count += 4; }
if (x > 100) { x /= 100; count += 2; }
if (x > 10) { x /= 10; count += 1; }
as it is fully unrolled. A good compiler may also unroll the while loop to a maximum of 10 iterations though.
#include<iostream>
using namespace std;
int main()
{
int count=0;
double x;
cout << "Enter a number: ";
cin >> x;
x /= 10;
while(x > 1)
{
count++;
x = x/10;
}
cout<<count+1;
}
Bar the suggestions of reading the number as a string, your current method of counting the number of significant decimal digits is fine. You could make it shorter, but this could arguably be less clear (extra set of parenthesis added to keep gcc from issuing warnings):
while((x = x/10))
count++;

Calculating mathematical constant e using while loop

I am currently doing a task in a book which asks me to calculate the mathematical constant e using the while loop. I managed that fairly easily, however I am having troubles calculating e^x, whereas the user inputs x and the degree of accuracy. The code I used for computing e is:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int degreeOfAccuracy, x = 1;
long double e = 1;
cout << "Enter degree of accuracy of mathimatical constant e: ";
cin >> degreeOfAccuracy;
while (x <= degreeOfAccuracy)
{
int conter = x;
int intial = x;
long double number = x;
int counter = 1;
while (conter > 1)
{
number = number*(intial-counter);
counter++;
conter--;
}
e += (1/number);
x++;
}
cout << endl << "The mathematical constantr e is: "
<< setprecision(degreeOfAccuracy) << fixed << e << endl;
system("pause");
return 0;
}
However, when I tried e^x the following code returned a completely wrong value:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int degreeOfAccuracy, x = 1, exponent;
long double e = 1;
cout << "Enter degree of accuracy of mathimatical constant e: ";
cin >> degreeOfAccuracy;
cout << "Enter the number of which you wish to raise to e: ";
cin >> exponent;
int temp = exponent;
while (x <= degreeOfAccuracy)
{
exponent = temp;
int conter = x;
int intial = x;
long double number = x;
int counter = 1;
while (conter > 1)
{
number = number*(intial-counter);
counter++;
conter--;
}
int counterr = 1;
while (counterr < x)
{
exponent *= exponent;
counterr++;
}
e += (exponent/number);
x++;
}
cout << endl << "The mathematical constantr e is: " << setprecision(degreeOfAccuracy) << fixed << e << endl;
system("pause");
return 0;
}
Any ideas where the calculations went wrong?
This line:
exponent *= exponent;
is wrong. It should be:
exponent *= temp;