for loop help. Terminates when it isnt supposed to. c++ - c++

I'm new to stackoverflow, but i did try to look for an answer and could not find it. I also can't seem to figure it out myself. So for a school C++ project, we need to find the area under a curve. I have all the formulas hardcoded in, so don't worry about that. And so the program is supposed to give a higher precision answer with a higher value for (n). But it seems that when I put a value for (n) thats higher than (b), the program just loops a 0 and does not terminate. Could you guys help me please. Thank you. Heres the code:
/* David */
#include <iostream>
using namespace std;
int main()
{
cout << "Please Enter Lower Limit: " << endl;
int a;
cin >> a;
cout << "Please Enter Upper Limit: " << endl;
int b;
cin >> b;
cout << "Please Enter Sub Intervals: " << endl;
int n;
cin >> n;
double Dx = (b - a) / n;
double A = 0;
double X = a;
for (X = a; X <= (b - Dx); X += Dx)
{
A = A + (X*X*Dx);
X = X * Dx;
cout << A << endl;
}
cout << "The area under the curve is: " << A << endl;
return 0;
}

a, b, n are integers. So the following:
(b - a) / n
is probably 0. You can replace it with:
double(b - a) / n

Since all the variables in (b - a) / n are int, you're doing integer division, which discards fractions in the result. Assigning to a double doesn't change this.
You should convert at least one of the variables to double so that you'll get a floating point result with the fractions retained:
double Dx = (b - a) / (double)n;

The other answers are correct. Your problem is probably integer division. You have to cast on of the operands to double.
But you should use static_cast<> instead of C-style casts. Namely use
static_cast<double>(b - a) / n
instead of double(b - a) / n or ((double) (b - a)) / n.

You are performing integer division. Integer division will only return whole numbers by cutting off the decimal:
3/2 == 1 //Because 1.5 will get cut to 1
3/3 == 1
3/4 == 0 //Because 0.5 will get cut to 0
You need to have at least one of the two values on the left or right of the "/" be a decimal type.
3 / 2.0f == 1.5f
3.0f / 2 == 1.5f
3.0f / 2.0f == 1.5f

Related

Why is the volume always calculated by zero?

I'm beginner in using functions, and I wrote this simple code. But I don't know why the volume is always calculated as zero.
#include <iostream>
using namespace std;
double area (double) ;
double volume (double) ;
int main () {
double radious ;
cout << "please enter the Radious \n" ;
cin >> radious ;
cout << "The area = " << area(radious) << "\n" ;
cin >> radious ;
cout << "The volume = " << volume(radious) << "\n" ;
cout << radious << "\n" ;
}
// defintion function of the area
double area (double R) {
return ( (4) * (3.14) * (R * R) ) ;
}
// defintion function of the volume
double volume (double R) {
return ( (3/4) * (3.14) * (R * R * R) ) ;
}
Your function volume will always return zero because 3 divided by 4 is 0 when interpreted as an integer. This is because casting any real value to integer will simply result in discarding decimal part. For example, 2.7 as int will be 2 not 3, there is no rounding, in a mathematical sense.
You can fix this in 2 ways:
A) reorder your equation so division will be the last operation you do, e.g. ((3.14*R*R*R*3)/4). Note that this is often necessary, when you want your result to be int, which is not the case here.
B) explicitly say that either (or both) 3 or 4 have to be treated as a real number (float/double) by adding .0, e.g. 3.0/4 or 3/4.0 or 3.0/4.0. This approach is better in your case since you expect double anyway.
For more information refer to Numeric conversions and this FAQ
The part 3/4 in your code performs an integer division. Integers cannot have floating points so usually the last part of integer is truncated, which leaves 0 in your case.
You can replace 3/4 with 3.0/4.0to make it work.
Good Luck!

Getting a C++ double function to report a message instead of returning a numerical when a certain condition is met

I am very new to C++, and am trying to create a pair of functions that will report two possible real solutions to a quadratic equation. I am also trying to enter a message into these functions that will display in lieu of a solution if no real solution exists.
The functions correctly report real solutions, but when a non-real solution appears, the program will return "The two possible real solutions to this problem are nan and nan," and my error message ("There is no real solution to that quadratic equation. Please enter a different set of numbers") does not show up in the terminal at all.
Here is my code. Thank you in advance for your help!
#include <iostream>
#include "std_lib_facilities.h" // from a Github page by Bjarne Stroustrup that corresponds with the Programming: Practices and Principles book. Note that I am learning this on my own; it is not for homework.
#include <cmath>
double quafo1 (double a, double b, double c)
{
if ((sqrt((b*b)-(4*a*c))) < 0)
{
cout << ("There is no real solution to that quadratic equation. Please enter a different set of numbers;/n");
}
else {
double x1 = ((b * -1) + sqrt((b * b) - (4 * a * c))) / (2 * a);
return x1;
}
}
double quafo2 (double a, double b, double c)
{
if ((sqrt((b*b)-(4*a*c))) < 0)
cout << ("There is no solution to that quadratic equation. Please enter a different set of numbers;");
else {
double x2 = ((b * -1) - sqrt((b * b) - (4 * a * c))) / (2 * a);
return x2;
}
}
double a;
double b;
double c;
int main()
{
cout << "This program will solve a quadratic equation as long as one or more real solutions are possible. Please enter values for a, b, and c (separated by spaces and followed by enter, e.g. 3 5 4), after which both possible answers for x will be provided. Please note that a cannot equal 0.\n";
while (cin >> a >> b >> c)
{
cout << "The two possible real solutions to this problem are " << quafo1(a, b, c) << " and " << quafo2(a,b,c) << ".\n";
}
}
The sqrt function will never return a negative value*, so your test (sqrt((b*b)-(4*a*c))) < 0 will never be TRUE. What you probably want to do is test if the argument to sqrtis negative:
if (((b*b)-(4*a*c))) < 0) {
cout << ("There is no solution to that quadratic equation. Please enter a different set of numbers;");
return nan("");
}
else {
//...
Alternatively, if that argument is negative, the sqrt function will return NaN, which you can test for with the isnan() function:
if (isnan(sqrt((b*b)-(4*a*c)))) {
cout << ("There is no solution to that quadratic equation. Please enter a different set of numbers;");
//...
Feel free to ask for further clarification and/or explanation.
Note: Strictly speaking, any (positive) number has two square roots, one positive and one negative: 2 x 2 = 4 but also -2 x -2 = 4.
You could just return NaN itself in those cases:
https://en.cppreference.com/w/cpp/numeric/math/nan
I would suggest a few changes to the programme that fix the issues you are having.
#include <iostream>
#include "std_lib_facilities.h"
// from a Github page by Bjarne Stroustrup that corresponds with the Programming: Practices and Principles book. Note that I am learning this on my own; it is not for homework.
#include <cmath>
double quafo1(double a, double b, double c) {
if ((b*b-4*a*c) < 0)
return sqrt(-1);
else
return ((b * -1) + sqrt((b * b) - (4 * a * c))) / (2 * a);
}
double quafo2(double a, double b, double c) {
if ((b*b-4*a*c) < 0)
return sqrt(-1);
else
return ((b * -1) - sqrt((b * b) - (4 * a * c))) / (2 * a);
}
double a;
double b;
double c;
int main()
{
cout << "This program will solve a quadratic equation as long as one or more real solutions are possible. Please enter values for a, b, and c (separated by spaces and followed by enter, e.g. 3 5 4), after which both possible answers for x will be provided. Please note that a cannot equal 0.\n";
while (cin >> a >> b >> c) {
double s1 = quafo1(a,b,c),
s2 = quafo2(a,b,c);
if (s1==s1 && s2==s2)
cout << "The two possible real solutions to this problem are " << s1 << " and " << s2 << '.' << endl;
else
cout << "There is no real solution to that quadratic equation. Please enter a different set of numbers." << endl;
}
}
First of all, as #Adrian mentioned above, you need to check whether b*b-4*a*c is negative or not and not its square root.
Second, the function must return something in all cases. Hence, you must have a return statement for when there are no real solutions. In those cases, you may simply return NaN. One way to do that would be returning sqrt(-1) as I did. In fact, you can simply return the solution to the quadratic equation, which would be NaN if no real solutions are possible because the square root of b*b-4*a*c is involved.
Now, in main, you may check if the returned value is NaN. To check for that, you can use isnan(), or check if it is equal to itself, which I did over here. I hope this solves your problem.
An indirect answer is that C++ has exceptions, precisely when you cannot return a value. You can define your own exception classes, but std::out_of_range makes perfect sense here.
Exceptions are thrown like throw std::out_of_range("There is no real solution to that quadratic equation."); and caught with try { ... } catch (std::exception& e) { std::cerr << e.what() << " Please enter a different set of numbers";}
cout << ("There is no real solution to that quadratic equation. Please enter a different set of numbers;/n");
This line should be terminated with "\n", not "/n". "<< endl;" could be used

I implemented my own square root function in c++ to get precision upto 9 points but it's not working

I want to get square root of a number upto 9 precision points so I did something like below but I am not getting correct precision. Here e is the precision which is greater than 10^9 then also ans is upto 5 precision points. What am I doing wrong here??
#include <iostream>
using namespace std;
long double squareRoot(long double n)
{
long double x = n;
long double y = 1;
long double e = 0.00000000000001;
while (x - y > e)
{
x = (x + y) / 2;
y = n / x;
}
cout << x << "\n";
return x;
}
int main()
{
int arr[] = {2,3,4,5,6};
int size = sizeof(arr)/sizeof(arr[0]);
long double ans = 0.0;
for(int i=0; i<size; i++)
{
ans += squareRoot(arr[i]);
}
cout << ans << "\n";
return 0;
}
The output is
1.41421
1.73205
2
2.23607
2.44949
9.83182
What should I do to get precision upto 9 points??
There are two places at which precision plays a role:
precision of the value itself
precision of the output stream
You can only get output in desired precision if both value and stream are precise enough.
In your case, the calculated value doesn't seem to be a problem, however, default stream precision is only five digits, i. e. no matter how precise your double value actually is, the stream will stop after five digits, rounding the last one appropriately. So you'll need to increase stream precision up to the desired nine digits:
std::cout << std::setprecision(9);
// or alternatively:
std::cout.precision(9);
Precision is kept until a new one is set, in contrast to e. g. std::setw, which only applies for next value.
try this
cout << setprecision(10) << x << "\n";
cout << setprecision(10) << ans << "\n";

C++ round a double up to 2 decimal places

I am having trouble rounding a GPA double to 2 decimal places. (ex of a GPA needed to be rounded: 3.67924) I am currently using ceil to round up, but it currently outputs it as a whole number (368)
here is what I have right now
if (cin >> gpa) {
if (gpa >= 0 && gpa <= 5) {
// valid number
gpa = ceil(gpa * 100);
break;
} else {
cout << "Please enter a valid GPA (0.00 - 5.00)" << endl;
cout << "GPA: ";
}
}
using the above code with 3.67924 would output 368 (which is what I want, but just without the period between the whole number and the decimals). How can I fix this?
To round a double up to 2 decimal places, you can use:
#include <iostream>
#include <cmath>
int main() {
double value = 0.123;
value = std::ceil(value * 100.0) / 100.0;
std::cout << value << std::endl; // prints 0.13
return 0;
}
To round up to n decimal places, you can use:
double round_up(double value, int decimal_places) {
const double multiplier = std::pow(10.0, decimal_places);
return std::ceil(value * multiplier) / multiplier;
}
This method won't be particularly fast, if performance becomes an issue you may need another solution.
If it is just a matter of writing to screen then to round the number use
std::cout.precision(3);
std::cout << gpa << std::endl;
see
floating points are not exactly represented so by internally rounding the value and then using that in your calculations you are increasing the inexactness.
When you are trying to store values upto n decimal values in a variable .
You have to multiple that value with 10^n and divide the same with 10^n.
Afterward use type operator to manipulate in the program.
Here is the example : -
float a,b,c,d,sum;
cin>>a>>b>>c>>d; // reading decimal values
sum=(a*b*c*d);
sum=round(sum*100)/100; // here it is for 2 decimal points
if((float)sum < (float) 9.58)
cout<<"YES\n";
else
cout<<"NO\n";
You can't round doubles to two decimal places. Doubles don't have decimal places. They have binary places, and they aren't commensurable with decimal places.
If you want decimal places, you must use a decimal radix, e.g. when formatting for output with printf("%.2f", ...).
Try this. But your cout statement in else condition, so it won't give the desired output for 3.67924.
if (cin >> gpa)
{
if (gpa >= 0 && gpa <= 5) {
// valid number
gpa = ceil(gpa * 100);
gpa=gpa/100;
break;
}
else
{
cout << "Please enter a valid GPA (0.00 - 5.00)" << endl;
cout << "GPA: ";
}
}
Example: you want 56.899999999999 to be output as a string with 2 decimal point which is 56.89.
First, convert them
value = 56.89 * 1000 = 5689
factor = 100
- 1 decimal point = 10
- 2 decimal point = 100
- 3 decimal point = 1000
etc
int integerValue;
int decimal;
std::string result;
function ( int value , int factor)
{
integerValue= (value / factor) * factor; //(5689 / 100) * 100 = 5600
decimal = value - integerValue; // 5689 - 5600;
result = std::to_string((int)(value/factor) + "." + std::to_string(decimal);
// result = "56" + "." + "89"
// lastly, print result
}
Not sure if this can help?
std::string precision_2(float number)
{
int decimal_part = (number * 100) - ((int)number * 100);
if (decimal_part > 10) {
return std::to_string((int)number) + "." + std::to_string(decimal_part);
} else {
return std::to_string((int)number) + ".0" + std::to_string(decimal_part);
}
}
Handles well for all positive floats. A minor modification will make it work for -ves as well.

C++ Pi Estimating Program Not Working Correctly

I am currently writing a program that estimates Pi values using three different formulas pictured here: http://i.imgur.com/LkSdzXm.png .
This is my program so far:
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
int main()
{
double leibniz = 0.0; // pi value calculated from Leibniz
double counter = 0.0; // starting value
double eulerall = 0.0; // pi value calculated from Euler (all integers)
double eulerodd = 0.0; // value calculated from Euler (odds)
int terms;
bool negatives = false;
cin >> terms;
cout << fixed << setprecision(12); // set digits after decimal to 12 \
while(terms > counter){
leibniz = 4*(pow(-1, counter)) / (2*counter+1) + leibniz;
counter++;
eulerall = sqrt(6/pow(counter+1,2)) + eulerall;
counter++;
eulerodd = (sqrt(32)*pow(-1, counter)) / (2*counter + 1) + eulerodd;
counter++;
cout << terms << " " << leibniz << " " << eulerall << " " << eulerodd <<endl;
}
if (terms < 0){
if(!negatives)
negatives=true;
cout << "There were " << negatives << " negative values read" << endl;
}
return 0;
}
The sample input file that I am using is:
1
6
-5
100
-1000000
0
And the sample output for this input file is:
1 4.000000000000 2.449489742783 3.174802103936
6 2.976046176046 2.991376494748 3.141291949057
100 3.131592903559 3.132076531809 3.141592586052
When I run my program all I get as an output is:
1 4.000000000000 1.224744871392 1.131370849898.
So as you can see my first problem is that the second and third of my equations are wrong and I can't figure out why. My second problem is that the program only reads the first input value and stops there. I was hoping you guys could help me figure this out. Help is greatly appreciated.
You have three problems:
First, you do not implement the Euler formulae correctly.
π2/6 = 1/12 + 1/22 + 1/32 + ...
eulerall = sqrt(6/pow(counter+1,2)) + eulerall;
The square root of the sum is not the sum of the square roots.
π3/32 = 1/13 + 1/33 + 1/53 + ...
eulerodd = (sqrt(32)*pow(-1, counter)) / (2*counter + 1) + eulerodd;
This is just... wrong.
Second, you increment counter three times in the loop, instead of once:
while(terms > counter){
...
counter++;
...
counter++;
...
counter++;
...
}
Third, and most fundamental, you didn't follow the basic rule of software development: start small and simple, add complexity as little at a time, test at every step, and never add to code that doesn't work.
my first problem is that the second and third of my equations are
wrong and I can't figure out why
Use counter++ just once. Apart from this Leibniz looks fine.
Eulerall is not correct, you should sum all factors and then do sqrt and multiplication at the end:
eulerall = 1/pow(counter+1,2) + eulerall;
// do sqrt and multiplication at the end to get Pi
The similar thing with eulerodd: you should sum all factors and then do sqrt and multiplication at the end.
My second problem is that the program only reads the first input value
and stops there.
In fact this is your first problem. This is because you are incrementing counter multiple times:
while(terms > counter){
leibniz = 4*(pow(-1, counter)) / (2*counter+1) + leibniz;
counter++; // << increment
^^^^^^^^^^
eulerall = sqrt(6/pow(counter+1,2)) + eulerall;
counter++; // << increment
^^^^^^^^^^
eulerodd = (sqrt(32)*pow(-1, counter)) / (2*counter + 1) + eulerodd;
counter++; // << increment
^^^^^^^^^^
cout << terms << " " << leibniz << " " << eulerall << " " << eulerodd <<endl;
}
You should increment counter just once.
You're using the same counter and incrementing it after each calculation. So each technique is only accounting for every third term. You should increment counter only once, at the end of the loop.
Also note that it is generally bad form to use a floating-point value as a loop counter. It only takes on integer values in your program, so you can just make it an int. Nothing else needs to change; the math will run the same because the int will promote to a double when you combine the two in math operations.
#include<iostream>
#include<conio.h>
#include<cmath>
using namespace std;
char* main()
{
while(1)
{
int Precision;
float answer = 0;
cout<<"Enter your desired precision to find pi number : ";
cin>>Precision;
for(int i = 1;i <= Precision;++i)
{
int sign = (pow((-1),static_cast<float>(i + 1)));
answer += sign * 4 * ( 1 / float( 2 * i - 1));
}
cout<<"Your answer is equal to : "<<answer<<endl;
_getch();
_flushall();
system("cls");
}
return "That is f...";
}