This question already has answers here:
Why does division result in zero instead of a decimal?
(5 answers)
Closed 8 years ago.
So i am trying to make one of my first very simple math programs in c++. the problem is that
i can't seem to get the function potodds to do what i want. There is no problem in getting it to multiple the two variables (x,y) that works perfectly fine. the problem occurs when i try to replace return x*y*100 with return (x/y)*100. in this case it always return the value 0?
Hopes that someone out there can help me pinpoint my mistake.
The code looks like this:
#include "stdafx.h"
#include <iostream>
int x;
int y;
int potodds(int x, int y) {
return x * y * 100; //(x/y)*100;
}
int main() {
using namespace std;
cout << "what's the size of the pot?" << endl;
cin >> y;
cout << "what's the size of the bet?" << endl;
cin >> x;
cout << "your potodds are:" << endl;
cout << potodds(x, y) << endl;
return 0;
}
Thanks to Ebyrob i got the solution.
the problem that I was having was that I was trying to divide an integer, that was assigned a decimal value and by definition an integer can only contain whole numbers. The result was that the integer was rounded down to zero.
x and y are defined as integral values. The integral division returns only the quotient. So if x is less than y then x /y will be equal to 0.
So it would be better to substitute expression ( x /y ) * 100 for ( 100 * x ) / y
Otherwise use float numbers
For example
( double )x / y * 100
Changing int to double should solve the problem but also "using namespace std;" is always outside of main when I program. I don't know if this affects anything but you might consider putting it above your main function because it might be causing a problem now or it might cause a problem in another program you make. I think it is a matter of it being global or private but I would have it outside of main so that any other functions you use can use it ( assuming I'm right ).
If you divide two integers, the result will be an integer (the quotient: the remainder is discarded).
So, 1 / 2 -> 0 instead of 0.5.
Note also that (1 / 2) * 100 is therefore 0 * 100 -> 0, while, as Vlad says,
100*1/2 -> 100/2 -> 50, which is what you want.
Related
This question already has answers here:
What is the behavior of integer division?
(6 answers)
Division of two numbers always returns an integer value
(3 answers)
Closed 3 months ago.
I dont understand why setprecision(2) not working when using if else statement
I tried doing this and it displays the else statement. I dont see any problem, maybe im using setprecision() wrong? I even displayed the quotient to prove that the if statement should be the one running.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float x = 2;
float y = 3;
float quotient, answer;
quotient = x / y;
cout << fixed << setprecision(2);
cout << quotient << " (is the answer)\n";
cout << " What is " << x << " divided by " << y << " ? ";
cin >> answer; // answer should be 0.67
if (quotient == answer)
cout << " You got the right answer! ";
else
cout << " Nice Try :( ";
return 0;
}
The line
quotient = x / y;
will assign the value of 0.0 to the variable quotient, because 2/3 is 0, using the rules of integer division. Therefore, if the user enters 0.67, this value will not compare equal to 0.0.
If you want the division 2/3 to evaluate to something like 0.6666666667, then you must make at least one of the operands a floating-point number, for example by using a cast:
quotient = static_cast<float>(x) / y;
However, even if you did this, your comparison would still not work, because the expression
cout << fixed << setprecision(2) << quotient;
will only change the way the variable quotient is printed. It will not change the actual value of the variable.
In order to round the actual value of the variable, you can use the function std::round. Note that this will only round to the nearest integer, so if you want to round to the nearest multiple of 0.01, then you will first have to multiply the number by 100 before performing the rounding operation. If you want, you can then divide the number by 100 again, to get the original number again, rounded to the nearest multiple of 0.01.
However, you should be aware that these operations may introduce slight floating-point inaccuracies. For this reason, it may be better to not require an exact match in the comparison
if (quotient == answer)
but to consider a deviation of up to 0.01 to still be considered a match. You can do this for example by changing the expression to this:
if ( std::abs( quotient - answer ) < 0.01 )
Note that you will have to #include <cmath> in order to use std::round and std::abs.
my goal is to turn a double's fraction part into an integer, for example: turn 0.854 into 854 or turn 0.9321 into 9321 (the whole part of the double is always 0)
i was doing it like this, but i dont know how to fill the while's parameters to make it stop when variable x becomes a whole number without a fraction:
double x;
cin >> x;
while(WHAT DO I TYPE HERE TO MAKE IT STOP WHEN X BECOMES A WHOLE NUMBER){
x *= 10;
}
it would be best if i could do it with a loop, but if it is not possible, i am open to other suggestions :)
That question has no answer in a mathematical/logical sense. You have to read how floating point numbers in computers work, see e.g.
https://en.wikipedia.org/wiki/Floating-point_arithmetic
and understand that they are not decimal point numbers in memory. A floating point number in memory consists of three actual numbers: significant * base^{exponent} and according to IEEE the base used is "2" in basically any modern floating point data, but in even more generality, the base can be anything. Thus, whatever you have in your mind, or even see on your screen as output, is a misleading representation of the data in memory. Your question is, thus, mainly a misconception of how floating point numbers in computers work...
Thus, what you specifically ask for does in general not exist and cannot be done.
However, there may be special application for output formatting or whatever where something like this may make sense -- but then the specific goal must be clearly stated in the question here. And in some of such cases, using a "string-based" approach, as you suggested, will work. But this is not an answer to your generic question and has the high potential to also mislead others in the future.
Actually, one way to make your question obvious and clear is to also specify a fixed desired precision, thus, numbers after the decimal point. Then the answer is quite trivially and correctly:
long int value = fraction * pow(10, precision);
In this scenario you know 100% what your are doing. And if you really like you could subsequently remove zeros from the right side...
int nTrailingZeros = 0;
while (value%10 == 0) {
value /= 10;
++nTrailingZeros;
}
However there is another principle problem on a numerical level: there is no mathematical difference between, e.g., 000003 and just 3, thus in any such application the input 0.000003 will give the same results as 0.0003 or 0.3 etc. This cannot be a desired functionality... it is pretty useless to ask about the *value of the fractional part of a floating point number. But, since we have a known precision`, we can do:
cout << setw(precision-ntrailing) << setfill('0') << value << endl;
which will fill in the eventually missing leading zeros.
See this complete tested test code
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
double v = 0.0454243252;
int precision = 14;
long int value = v*pow(10,precision);
cout << value << endl;
// 4542432520000
int nTrailingZeros = 0;
while (value%10 == 0) {
value /= 10;
++nTrailingZeros;
}
cout << value << endl;
// 454243252
cout << setw(precision-ntrailing) << setfill('0') << value << endl;
// 0454243252
}
Here is a possible approach:
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
int main()
{
cout << "Enter Number: ";
double user_input;
cin >> user_input;
int user_input_to_int = int(user_input);
double decimal_value = user_input - user_input_to_int;
ostringstream oss;
oss << std::noshowpoint << decimal_value;
string num_str = oss.str();
int str_length = num_str.size()-2;
int multiplier = 1;
for (int x = 0; x < str_length; x++)
{
multiplier *= 10;
}
cout << "\n";
cout << "Whole number: " << user_input_to_int << endl;
cout << "Decimal value: " << decimal_value*multiplier << endl;
}
Compare the difference between double and integer part. It is working only if x is less than 2^63.
while (x - long long(x) > 0)
find 2 real numbers find the fractional part smaller than these numbers
I'm trying to make a code that do a simple operation of probability, but it always return the same value(3221225725). I rewrote and changed the code several times (changed variables types, stopped using switch, created a variable for x-y, etc) but it keeps returning the same value. Do someone knows why it keeps doing this?
#include<iostream>
#include<cmath>
using namespace std;
float z;
float y;
float a = z - y;
int factorial(float x)
{
if (x == 1)
{
return 1;
}
else
{
return x * factorial(x - 1);
}
}
int main()
{
cout << "Insert total number of elements or press 0 to exit" << endl;
cin >> z;
cout << "Insert total number of attempts or press 0 to exit" << endl;
cin >> y;
if (z > 0 && y > 0)
{
return (factorial(z) / (factorial(y)) * (factorial(a)));
}
else
{
return 0;
}
}
Okay there are several small issues with your code, but together they make a whole heap of problems.
Here is a "working" version that solves most of your problems, comments in the code indicate what mistakes you made: https://coliru.stacked-crooked.com/a/0716e3a1fc7ecafc
Big issues you made:
You initialized "a" with values from "z" and "y" before they were initialized, this means "a" contained uninitialized memory, and you will get random results.
You are doing a direct comparison with a floating point number using "==" floating point numbers are not perfect representations, and the introduce small amounts of error with each math operation. When comparing floating point numbers you almost always need to compare them with some reasonable tolerance like within .00001.
You were using the "return" of your main function to try to pass out a value. The return value from the main function of a program is a flag for the operating system that indicates how the program ran; 0 means the program ran fine, any other value indicates an error code. Instead you want to print the value out.
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'
This question already has answers here:
cin >> fails with bigger numbers but works with smaller ones?
(4 answers)
Closed 5 years ago.
I have recently made a program in C++ that counts a sum of digits in an input number (code below). The program works this way. A user is asked to input a natural number x. Then the program is put into a while loop which is meant to proceed until the x reaches 0. The y is a simple equation which determines the last digit of a number (i.e. x=123, y=3). D_sum is the sum of digits in x (i.e. x=123, d_sum=3).
The x=(x-y)/10 is used to help to calculate next digit (i.e. x=(123-3)/10=120/10=12). The program works fine until you input a number with more than 10 digits (screen below).
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int x,y;
int d_sum = 0;
cout << "x= ";
cin >> x;
while(x > 0)
{
y=x % 10;
d_sum++;
x = (x - y) / 10;
}
cout << d_sum << endl;
system("pause");
return 0;
}
Screen:
Take a look at http://en.cppreference.com/w/cpp/language/types
, looks like on your platform int is 32 bits. e.g. if int is 32 bit, maximum number it may be able to store would 2^31 = 2147483648.