C++ round a double up to 2 decimal places - c++

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.

Related

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";

Homework Assistance, program not returning a value

Im having trouble with the function taylor2 not returning a value if i input anything over 2. If I enter 0-2 it outputs the correct value but anything over 2 and I just get a flashing underscore with no data returned.
void taylor2(double x)
{
double total = 1;
int i = 0;
int count = 1;
double temp = 1;
do
{
{
if (i % 2 == 1)
{
temp = (pow(x, i * 2 + 2) / factorial(i * 2 + 2));
total += temp;
}
else {
temp = (pow(x, i * 2 + 2) / factorial(i * 2 + 2));
total -= temp;
}
}
count++;
i++;
} while (fabs(temp) >= .0001);
cout << "The last recoreded temporary value was: "<<temp << endl;
cout << "The computed value for cosine is : "<< total << endl;
cout << "It took " <<count << " values to calculate the value of the function to .0001 places"<< endl;
cout << endl;
}
I suspect that factorial is returning an int. If int is 32 bit (very common), then factorial will overflow once the argument reaches 13 (i = 5 in your case). Signed integer overflow is undefined behaviour in C++.
You could use a std::uint64_t (an unsigned 64 bit integer). This will allow you to evaluate a few larger factorials.
For more reference, see Calculating large factorials in C++
Better still, use a recurrence relation between your Taylor terms.

for loop help. Terminates when it isnt supposed to. 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

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...";
}

Calculation issue in C++

So in this program i am trying to print out the standard deviation of a set of numbers the user enters in. The formula to calculate standard deviation is correct (or as correct as it needs to be) so that is not the problem, but when i run the program everything goes well until the console prints out the results. It prints that totalStandardDeviation = nan
what exactly does than mean? is nan the same as nil? has it lost the value somehow and not been able to find it? thanks for any help you may provide.
#include <iostream>
#include <cmath>
using namespace std;
double returnStandardDeviation(double x, int counter);
double total;
int userInput = 1;
int counter = 0;
double x;
double x1;
double x2;
double standardDeviation;
double totalStandardDeviation;
int main(int argc, const char * argv[])
{
cout << "Please enter a list of numbers. When done enter the number 0 \n";
cin >> userInput;
while (userInput != 0) // As long as the user does not enter 0, program accepts more data
{
counter++;
x = userInput;
returnStandardDeviation( x, counter); // send perameters to function
cout << "Please enter next number \n";
cin >> userInput;
}
cout << "The standard deviation of your "
<< counter
<< " numbers is : "
<< returnStandardDeviation(x, counter);
return 0;
}
double returnStandardDeviation(double x, int counter)
{
x1 += pow(x,2);
x2 += x;
totalStandardDeviation = 0;
totalStandardDeviation += (sqrt(counter * x1 - pow(x2,2))) / (counter * (counter - 1));
return totalStandardDeviation;
}
NaN stands for "Not a number".
NaN can e.g. be the result of:
- Dividing by zero
- Taking the square root of a negative number
In your function, both of these could happen. Division by zero e.g. when counter is <= 1; and x1 and x2 are uninitialized (+= adds the value on the right to their current value - which was never set, and is therefore random gibberish), which can easily lead to your function trying to take the square root of some value < 0.
This expression
counter * x1 - pow(x2,2)
can very easily yield a negative number. You then proceed to take its square root. This would result in a nan.
Next, this one
counter * (counter - 1)
yields 0 when counter is 1. Dividing by zero gives nan.
Your formula is wrong. You are either dividing by zero or taking the square root of a negative number.
Check your formula!
Additional info:
NaN is "Not a number". It is an IEEE floating point value that signals an invalid results, like log(-1), or sqrt(-4).
Additionally, know that Positive Infinity and Negative Infinity are also floating point values.