Circle Area C++ Truncation Calculation Problem [closed] - c++

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 last month.
This post was edited and submitted for review last month and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I tried to make a console application in C++ that calculates the area of a circle using the equation:
pi times radius squared.
By the way, I use Visual Studio to make console applications.
These are the steps the program takes:
Output some text, like the title, the equation.
Get input from the user for the radius and store it in a double(float) variable.
Use the equation: pi times radius squared. But replace the radius with the input from the user.
Output the results.
Sometimes, an annoying round off error(truncation) sometimes rounds off the decimals and I am frustrated.
Here is my code:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <string>
using namespace std;
int main() {
double input = NULL;
const double pi = 3.14;
cout << "Enter in your radius: " << input << endl;
cin >> input;
double acc = pi * pow(2, input);
cout << "The area: " << acc << ". Don't forget to add the measurement type! (example: cm, in)" << endl;
}
I used to have a int for the input variable but I changed it to a double(float) variable. Because it is a double(big float), I thought that it would stop the truncation problem. Still the truncation(round off) problem still sometimes occurs.
I wanted it to output a result that is not rounded, and still am getting the round off error

You can use std::setprecision() to force to display a set number of digits, for example:
#include <iomanip>
// ...
double acc = pi * input * input;
int precision = log10(acc) + 7; // 7 = number of decimals + 1
cout << "The area: " << setprecision(precision) << acc << ". Don't forget to add the measurement type! (example: cm, in)" << endl;
Will yield 6 decimal digits.
Ex: for input : 211.123456 will print out
The area: 139959.576934. Don't forget to add the measurement type! (example: cm, in)
Note that the maximum precision for doubles is 19 digits altogether.

Related

C++ Not Calculating Precisely [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Why would a c++ double be limiting itself to 5 decimal places?
(1 answer)
c++ long double printing all digits with precision
(1 answer)
Closed 2 years ago.
I've written this code but it is not giving the Exact (Precise) answer. It automatically rounds up the answer. Please take a look at this and help me solve this issue. When I calculate with calculator it shows me different results and when I calculate with my program it show me different results which I think are not Exact, I want exact results. The value I am using for rad1 = 281.531 and rad2 = 118.213. See the attached image. Note: This is the first time I am asking a question online, so please ignore my mistakes.
#include <iostream>
using namespace std;
double circleArea (double);
int main()
{
double rad1,rad2;
double ringarea;
cout << "Please enter the radius of Outer Circle: ";
cin >> rad1;
cout << "Please enter the radius of Inner Circle: ";
cin >> rad2;
ringarea = circleArea(rad1) - circleArea(rad2);
cout << "The area of the Outer Circle is: " << circleArea(rad1) << endl;
cout << "The area of the Inner Circle is: " << circleArea(rad2) << endl;
cout << "The area of the Ring is: " << ringarea << endl;
return 0;
}
double circleArea (double r)
{
double pi = 3.1415926;
return (pi * r * r);
}
Screenshot of Output

My calculus about mean and standard deviation doesn't work [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 2 years ago.
Improve this question
let's assume that I have the sum of the integer in my variable mean and the sum of the scarred integer in my variable std. I want to have the mean and the standard deviation with respectively 3 and 4 numbers after the decimals point. But I don't have the expected value at all for the mean and the std :
int main(){
mean = double(int((double(mean)/(n-1))*1000))/1000;
std = double(int(sqrt(double(std)/(n-1) - mean*mean)*10000))/10000;
return 0;
}
I put double(int(....*1000))/1000 to have the 3 numbers after the decimal point.
The first issue was to correct the formulas:
you need to divide by n for the mean, and by n-1 for the variance.
To get exactly the expected number of figures after the decimal point, it is better to
perform the calculations with best possible precision, and then for the final display to combine
<< std::fixed << set precision (3) << ...
With this solution, you get some additional zeros at the end if necessary.
Output:
mean = 1.090
std deviation = 0.0265
The code:
#include <iostream>
#include <cmath>
#include <iomanip>
int main(){
double sum_x = 5.45;
double sum_x2 = 5.9433;
int n = 5;
double mean = sum_x/n;
double variance = sum_x2/n - mean*mean;
variance *= double (n)/(n-1); // correction to get an unbiased estimation
double std_deviation = std::sqrt (variance);
std::cout << "mean = " << std::fixed << std::setprecision(3) << mean << "\n";
std::cout << "std deviation = " << std::fixed << std::setprecision(4) << std_deviation << "\n";
return 0;
}

Simple C++ calculation giving odd outputs [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm working on a C++ program to calculate a speeding ticket fine for different speeds.
"The speeding ticket fine policy in (City) is $50 plus $5 for each mph over the limit plus a penalty of $250 for any speed over 85 mph. Write a program that accepts a speed limit and a clocked speed and either prints a message indicating the speed was legal or prints the amount of the fine, if the speed is illegal.In the program, you also need to display whether the number of miles over the speed limit, and if he/she is driving over 85 mph."
Here's my code:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double speedlimit,clockedspeed,speeddifference,fineunder85,fineover85;
speeddifference = clockedspeed-speedlimit;
fineunder85 = (speeddifference*5)+50;
fineover85 = (speeddifference*5)+300;
cout<<"Enter the speed limit: "<<endl;
cin>>speedlimit;
cout<<"Enter the clocked speed: "<<endl;
cin>>clockedspeed;
if ((clockedspeed > speedlimit) && (clockedspeed > 85))
{
cout<<"The clocked speed is: Illegal"<<endl;
cout<<"Miles over the speed limit: "<<setprecision(2)<<speeddifference<<endl;
cout<<"Driving over 85 mph: Yes"<<endl;
cout<<"The fine is: $"<<setprecision(2)<<fineover85<<endl;
}
else {
cout<<"The clocked speed is: Illegal"<<endl;
cout<<"Miles over the speed limit: "<<setprecision(2)<<speeddifference<<endl;
cout<<"Driving over 85 mph: No"<<endl;
cout<<"The fine is: $"<<setprecision(2)<<fineunder85<<endl;
}
}
I'm getting weird outputs for (speeddifference) like "-7e-310" and the fine isn't adding the additional penalty ($5/mile over the limit) but is only outputting "$50" or "$300".
Just looking for help, I've searched everywhere and I've come up short.
ty all
You're calculating the speed difference and fines before you even input the numbers! Remember that the program runs line by line (without functions, classes, etc. just procedural programming). Furthermore, you declare the variables without defining them with a set value which is why you are getting random values.
Move the:
speeddifference = clockedspeed-speedlimit;
fineunder85 = (speeddifference*5)+50;
fineover85 = (speeddifference*5)+300;
to after you receive input.
Edit:
There seems to be numerous other errors and I've tried my best effort to fix all of them. Here's a reworked version.
#include <iostream>
int main()
{
double fine = 0;
double speed_limit;
double clocked_speed;
std::string over_85 = "no";
std::cout << "Speed limit:\n";
std::cin >> speed_limit;
std::cout << "Clocked speed:\n";
std::cin >> clocked_speed;
double speed_difference = clocked_speed - speed_limit;
fine += 50 + speed_difference * 5;
if (clocked_speed > 85) {
fine += 250;
over_85 = "yes";
}
if (clocked_speed <= speed_limit) {
std::cout << "\nLegal\n";
}
else {
std::cout << "\nIllegal\n"
<< "Miles over: " << speed_difference << '\n'
<< "Over 85mph: " << over_85 << '\n'
<< "Fine: $" << fine << '\n';
}
}
Changes:
Set a variable string over_85; to remove need of complicated if statement.
Remove need for two different fines and instead have one fine with an if statement to add the $250 fine if necessary.

How to cout a float/double with dynamic precision? [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 7 years ago.
Improve this question
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
float a = 3.14159;
double b = 3.14159;
cout.precision(6);
cout << a << endl; //3.14159
cout << b << endl; //3.14159
cout.precision(10);
cout << a << endl; //3.141590118
cout << b << endl; //3.14159
cout.precision(20);
cout << a << endl; //3.141590118408203125
cout << b << endl; //3.1415899999999998826
return 0;
}
Can anyone explain the difference between float and double?
How do we print float/double with dynamic precision?
Assuming I have your definition of dynamic correct something like this should work:
void print(float toPrint, int precision)
{
cout.precision(precision);
cout << toPrint <<endl;
}
cout.precision only changes the precision of the printing, it doesn't actually affect how precise the numbers are. If you print with more digits than your numbers have precision, you will get inaccurate digits.
Of course, cout.precision also only changes the maximum precision of the printing. To force it to print trailing zeros, do something like this:
void print(float toPrint, int precision)
{
cout.precision(precision);
cout << fixed;
cout << toPrint <<endl;
}
The difference between a float and a double is that a double is approximately twice as precise as a float. In general, a float has something like 7 or 8 digits of precision, and a double has 15 or 16 digits of precision.
If I'm reading your question correctly you are wondering why both floats and doubles lose precision after you adjust cout.precision.
This occurs because floating point numbers are stored in binary differently than normal whole numbers. A common example of why this matters is that the number 0.6 is stored in binary as 0011111100101.... This, like 0.6666666... in decimal, is an infinitely long number. Thus, your computer needs to decide at what point it should round/approximate the value. When you declare and initialize your floating point numbers a and b, the computer knows that it does not need to cram any value other than 3.14159 into the variable. However, when you then change cout.precision, the computer thinks it needs to round the floating point at a later location. Furthermore, floats are only 16 bits so it will almost always be less precise than the double, which is 32 bits. See here for their ranges.
Obviously to get the correct precision you shouldn't adjust cout.precision to be greater than the number of digits of your variable. However if you want to adjust the precision and just print out a bunch of zeroes after the end of your initial variable value, just use cout << fixed << setprecision(number). See below:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
float a = 3.14159;
double b = 3.14159;
cout.precision(6);
cout << a << endl; //3.14159
cout << b << endl; //3.14159
cout << fixed << setprecision(10);
cout << a << endl; //3.141590118
cout << b << endl; //3.141590000
return 0;
}
Edit: Another option is to use limits.
It doesn't make sense to have a "dynamic precision" where all digits different from 0 are displayed. That mode would have issues with fractional numbers that have infinite decimal digits, like the result of 1.0 / 3.
The best you can do is to set the maximum precision you are willing to see with precision, just like in your example.

Why does this code add an extra zero to my 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 8 years ago.
Improve this question
The following code
#include "stdafx.h"
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool qualities(double number){
//function qualities, irrelevant to question
}
int main(){
double pandigital = 123456789;
double sum = 0;
string strpan = to_string(pandigital);
while (next_permutation(strpan.begin(), strpan.end())){
cout << strpan << endl;
if (qualities(pandigital)){
sum += pandigital;
}
next_permutation(strpan.begin(), strpan.end());
break;
}
cout << "sum is " << sum << endl;
cin.get();
}
has the following problems beginning at this piece of code
double pandigital = 123456789;
double sum = 0;
string strpan = to_string(pandigital);
while (next_permutation(strpan.begin(), strpan.end())){
cout << strpan << endl;
The problem is strpan has an extra zero appended to it, which is an error. If I add a zero to pandigital so we have 1234567890, it will still append an extra zero.
Zero comes from std::to_string converting a double to string: rather than producing "123456789", it makes "123456789.0".
To fix this problem, declare pandigital as int, or add a cast when converting it to a string:
string strpan = to_string((int)pandigital);
With this issue out of the way, you have another fix to make: each iteration of your while loop calls next_permutation twice - once in the header of the loop, and once in the body. You should remove the invocation that you perform in the body of the loop.
Finally, recall that in order to go through all possible permutations the initial call of next_permutation should be made when the range is sorted. It is not a problem for your number, because the digits are arranged in ascending order, but it may become an issue if you start with a different number.