Why is the volume always calculated by zero? - c++

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!

Related

Cos function giving me zero

I am a complete beginner in programming and I was given the following assignment:
Write a C++ program that computes a pair of estimates of π, using a sequence of inscribed and circumscribed regular polygons. Halt after no more than 30 steps, or when the difference between the perimeters of the circumscribed and inscribed polygons is less than a tolerance of ε=10⁻¹⁵. Your output should have three columns, for the number of sides, the perimeter of an inscribed polygon, and perimeter of the circumscribed polygon. For the last two columns, display 14 digits after the decimal point.
well, I decided to use the law of cos to find the lengths of the sides of the polygon but when I was testing out my program I realized the line:
a = cos(360 / ngon);
keeps giving me a zero as the output which makes everything else also zero and I am not sure what is wrong please help.
P.S. Sorry if the program looks really sloppy, I am really bad at this.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <fstream>
#define _USE_MATH_DEFINES
#include <math.h>
#include <cmath>
using namespace std;
int main()
{
char zzz;
int ngon = 3, a, ak;
double insngon = 0.0;
double cirngon = 0.0;
cout << "Number of Sides" << "\t\t\t" << "Perimeter of insribed region" << "\t\t\t" << "Perimeneter of circumscribed polygon" << "\t\t" << "\n";
while (ngon <= 30)
{
a = cos(360 / ngon);
ak = pow(.5, 2) + pow(.5, 2) - 2 * .5*.5*a;
insngon = (ak*ngon);
cirngon = (ak / (sqrt(1 - pow(ak, 2))));
cout << fixed << setprecision(14) << ngon << " " << insngon << " " << cirngon << endl;
ngon++;
if (cirngon - insngon <= pow(10.0, -15));
cin >> zzz;
return 0;
}
cout << "\nEnter any character and space to end ";
cin >> zzz;
return 0;
}
One issue is that you declared integers, yet you are using them in the call to cos here:
int ngon = 3, a, ak;
//...
a = cos(360 / ngon);
Since a is an integer, the return value of cos (which is of type double) will be truncated. Also, since ngon is an integer, the 360 / ngon will also truncate.
The fix is to make a a double, and divide 360.0 by ngon to prevent the truncation:
int ngon = 3, ak;
double a;
//...
a = cos(360.0 / ngon);
The other issue, as pointed out in the comments is that the trigonometric functions in C++ use radians as the argument, not degrees. You need to change the argument to the equivalent value in radians.
Another issue is that you're using pow to compute values that are constant. There is no need to introduce an unnecessary function call to compute constant values. Just define the constants and use them.
For example:
const double HALF_SQUARED = 0.25
const double EPSILON_VALUE = 10.0e-15;
and then use HALF_SQUARED and EPSILON_VALUE instead of the calls to pow.
Also, pow is itself a floating point function, thus can produce results that are not exact as is discussed by this question . Thus pow(ak, 2) should be replaced with simply ak * ak.
Use float a; (or double a) instead of int a.
Here the return type of a is int
And calculating
a = cos(360/ngon)
Is equivalent to a= cos(120) that is the result of cos(120) is 0.8141 and being a integer type "a" will only store the integer part it.
Therefore 'a' will be 0 and discarding floating value.
Also use double ak; instead of int ak;.
Because here pow function has been used which have return type 'double'

How to express large numbers to two decimal places in C++ Calculator

I am trying to write a calculator in C++ that does the basic functions of /, *, -, or + and shows the answer to two decimal places (with 0.01 precision).
For example 100.1 * 100.1 should print the result as 10020.01 but instead I get -4e-171. From my understanding this is from overflow, but that's why I chose long double in the first place!
#include <iostream>
#include <iomanip>
using namespace std;
long double getUserInput()
{
cout << "Please enter a number: \n";
long double x;
cin >> x;
return x;
}
char getMathematicalOperation()
{
cout << "Please enter which operator you want "
"(add +, subtract -, multiply *, or divide /): \n";
char o;
cin >> o;
return o;
}
long double calculateResult(long double nX, char o, long double nY)
{
// note: we use the == operator to compare two values to see if they are equal
// we need to use if statements here because there's no direct way
// to convert chOperation into the appropriate operator
if (o == '+') // if user chose addition
return nX + nY; // execute this line
if (o == '-') // if user chose subtraction
return nX - nY; // execute this line
if (o == '*') // if user chose multiplication
return nX * nY; // execute this line
if (o == '/') // if user chose division
return nX / nY; // execute this line
return -1; // default "error" value in case user passed in an invalid chOperation
}
void printResult(long double x)
{
cout << "The answer is: " << setprecision(0.01) << x << "\n";
}
long double calc()
{
// Get first number from user
long double nInput1 = getUserInput();
// Get mathematical operations from user
char o = getMathematicalOperation();
// Get second number from user
long double nInput2 = getUserInput();
// Calculate result and store in temporary variable (for readability/debug-ability)
long double nResult = calculateResult(nInput1, o, nInput2);
// Print result
printResult(nResult);
return 0;
}
setprecision tells it how many decimal places you want as an int so you're actually setting it to setprecision(0) since 0.01 get truncated. In your case you want it set to 2. You should also use std::fixed or you'll get scientific numbers.
void printResult(long double x)
{
cout << "The answer is: " << std::fixed << setprecision(2) << x << "\n";
}
working example
It is not due to overflow you get the strange result. Doubles can easily hold numbers in the range you are showing.
Try to print the result without setprecision.
EDIT:
After trying
long double x = 100.1;
cout << x << endl;
I see that it doesn't work on my Windows system.
So I searched a little and found:
print long double on windows
maybe that is the explanation.
So I tried
long double x = 100.1;
cout << (double)x << endl;
which worked fine.
2nd EDIT:
Also see this link provided by Raphael
http://oldwiki.mingw.org/index.php/long%20double
The default floating point presentation switches automatically between presentation like 314.15 and 3.1e2, depending on the size of the number and the maximum number of digits it can use. With this presentation the precision is the maximum number of digits. By default it's 6.
You can either increase the maximum number of digits so that your result can be presented like 314.15, or you can force such fixed point notation by using the std::fixed manipulator. With std::fixed the precision is the number of decimals.
However, with std::fixed very large and very small numbers may be pretty unreadable.
The setprecision() manipulator specifies the number of digits after the decimal point. So, if you want 100.01 to be printed, use setprecision(2).
When you use setprecision(0.01), the value 0.01 is being converted to int, which will have a value of 0.
It wouldn't have hurt if you had actually read the documentation for setprecision() - that clearly specifies an int argument, not a floating point one.

Am I doing double to float conversion here

const double dBLEPTable_8_BLKHAR[4096] = {
0.00000000000000000000000000000000,
-0.00000000239150987901837200000000,
-0.00000000956897738824125100000000,
-0.00000002153888378764179400000000,
-0.00000003830892270073604800000000,
-0.00000005988800189093979000000000,
-0.00000008628624126316708500000000,
-0.00000011751498329992671000000000,
-0.00000015358678995269770000000000,
-0.00000019451544774895524000000000,
-0.00000024031597312124120000000000,
-0.00000029100459975062165000000000
}
If I change the double above to float, am I doing incurring conversion cpu cycles when I perform operations on the array contents? Or is the "conversion" sorted out during compile time?
Say, dBLEPTable_8_BLKHAR[1] + dBLEPTable_8_BLKHAR[2] , something simple like this?
On a related note, how many trailing decimal places should a float be able to store?
This is c++.
Any good compiler will convert the initializers during compile time. However, you also asked
am I incurring conversion cpu cycles when I perform operations on the array contents?
and that depends on the code performing the operations. If your expression combines array elements with variables of double type, then the operation will be performed at double precision, and the array elements will be promoted (converted) before the arithmetic takes place.
If you just combine array elements with variables of float type (including other array elements), then the operation is performed on floats and the language doesn't require any promotion (But if your hardware only implements double precision operations, conversion might still be done. Such hardware surely makes the conversions very cheap, though.)
Ben Voigt answer addresses your question for most parts.
But you also ask:
On a related note, how many trailing decimal places should a float be able to store
It depends on the value of the number you are trying to store. For large numbers there is no decimals - in fact the format can't even give you a precise value for the integer part. For instance:
float x = BIG_NUMBER;
float y = x + 1;
if (x == y)
{
// The code get here if BIG_NUMBER is very high!
}
else
{
// The code get here if BIG_NUMBER is no so high!
}
If BIG_NUMBER is 2^23 the next greater number would be (2^23 + 1).
If BIG_NUMBER is 2^24 the next greater number would be (2^24 + 2).
The value (2^24 + 1) can not be stored.
For very small numbers (i.e. close to zero), you will have a lot of decimal places.
Floating point is to be used with great care because they are very imprecise.
http://en.wikipedia.org/wiki/Single-precision_floating-point_format
For small numbers you can experiment with the program below.
Change the exp variable to set the starting point. The program will show you what the step size is for the range and the first four valid numbers.
int main (int argc, char* argv[])
{
int exp = -27; // <--- !!!!!!!!!!!
// Change this to set starting point for the range
// Starting point will be 2 ^ exp
float f;
unsigned int *d = (unsigned int *)&f; // Brute force to set f in binary format
unsigned int e;
cout.precision(100);
// Calculate step size for this range
e = ((127-23) + exp) << 23;
*d = e;
cout << "Step size = " << fixed << f << endl;
cout << "First 4 numbers in range:" << endl;
// Calculate first four valid numbers in this range
e = (127 + exp) << 23;
*d = e | 0x00000000;
cout << hex << "0x" << *d << " = " << fixed << f << endl;
*d = e | 0x00000001;
cout << hex << "0x" << *d << " = " << fixed << f << endl;
*d = e | 0x00000002;
cout << hex << "0x" << *d << " = " << fixed << f << endl;
*d = e | 0x00000003;
cout << hex << "0x" << *d << " = " << fixed << f << endl;
return 0;
}
For exp = -27 the output will be:
Step size = 0.0000000000000008881784197001252323389053344726562500000000000000000000000000000000000000000000000000
First 4 numbers in range:
0x32000000 = 0.0000000074505805969238281250000000000000000000000000000000000000000000000000000000000000000000000000
0x32000001 = 0.0000000074505814851022478251252323389053344726562500000000000000000000000000000000000000000000000000
0x32000002 = 0.0000000074505823732806675252504646778106689453125000000000000000000000000000000000000000000000000000
0x32000003 = 0.0000000074505832614590872253756970167160034179687500000000000000000000000000000000000000000000000000
const double dBLEPTable_8_BLKHAR[4096] = {
If you change the double in that line to float, then one of two things will happen:
At compile time, the compiler will convert the numbers -0.00000000239150987901837200000000 to the float that best represents them, and will then store that data directly into the array.
At runtime, during the program initialization (before main() is called!) the runtime that the compiler generated will fill that array with data of type float.
Either way, once you get to main() and to code that you've written, all of that data will be stored as float variables.

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

for loop multiple variable, second variable not updating

I am trying to write two loops in one for loop so I looked up the syntax for multiple variables in the for loop
the problem is the second variable l isn't updating I don't know why
#include<iostream>
using namespace std;
int main ()
{
float vsum=0, lsum=0;
double nsum=0, msum=0;
float v=1, l=100000000;
for (v, l ; v<= 100000000, l >= 1 ; v++, l--)
{
vsum= vsum + 1/v;
nsum= nsum + 1/v;
lsum= lsum + 1/l;
msum= msum+ 1/l;
}
cout << " The float sum of all numbers 1 through 1/100000000 is " << vsum << endl;
cout << " The double sum of all numbers 1 through 1/100000000 is " << nsum << endl;
cout << "The float sum of all numbers 1/100000000 through 1/1 is " << lsum << endl;
cout << "The double sum of all numbers 1/100000000 through 1/1 is " << msum << endl;
cin >> vsum;
}
I guess your question is that after
float f = 100000000;
why does --f; leave f unchanged?
The answer is due to the granularity of float. The float does not have enough accuracy to store every possible integer. Clearly a 32-bit float cannot store as many integer values as a 32-bit int, for example.
The further away from 0 you get, the larger the gap gets between successive possible values of a float. On your system 100000000 - 1 is still larger than the next possible value of float below 100000000.
The rules of C++ are that when the result of the calculation is not representable exactly by a float, then it's implementation-defined whether the next-lowest value or the next-highest value is used. (So your compiler should actually document what happens here). In this case your system is using the next-highest value.
To get your intended results, make v and l be integral types, and do a float conversion in the actual calculation, e.g.
vsum += 1.f/v;
nsum += 1.0/v;
As dasblinkenlight mentions, you are only checking the second condition, but the second variable is updating just fine. Here is an abridged example that proves this.
#include<iostream>
using namespace std;
int main ()
{
float vsum=0, lsum=0;
double nsum=0, msum=0;
float v=1, l=10;
for (v, l ; v<= 10, l >= 1 ; v++, l--)
{
cout << v << " " << l << endl;
}
}
Output:
1 10
2 9
3 8
4 7
5 6
6 5
7 4
8 3
9 2
10 1