I have the following in a program (part of a much larger function, but this is the relevant testing bit):
int test = 100 + (100 * (9 / 100));
sprintf (buf, "Test: %d\n\r", test);
display_to_pc (buf, player);
Basically it amounts to:
x = a + (a * (b / 100))
Where a is a given figure, b is a percentage modifier, and x is the result (the original plus a percentage of the original)... I hope that makes sense.
It gives me:
Test: 100
I thought the math in my head might be wrong, but I've checked several calculators and even the expression evaluator in my IDE, and they all give me the expected result of 109 for the first expression.
Can anyone enlighten me as to what I'm missing here?
Thanks much. :)
Replace
int test = 100 + (100 * (9 / 100));
with
int test = 100 + (100 * 9 / 100);
// x = a + (a * b / 100)
and it will work as expected. 9 / 100 is performed using integer division; the nearest integer to .09 is 0 (and 0 * 100 is still 0).
Doing the multiplication first results in 900 / 100, which gives you the 9 that you were expecting.
If you need more than integer precision, you may need to go the floating point route.
You're using integer math.
9/100 = 0.
100 + (100 * (0) = 100.
Your calculators use floating point math, and can handle decimals appropriately.
As others have pointed out, the problem is that you are doing integer arithmethic. You need to do the calculation as floating point by casting the variable to double or using a double constant, then allow truncation to give you just the integer portion.
x = a + (a * (b / 100.0));
or
x = a + (a * ((double)b / 100)));
Your mistake is that 9 / 100 is interpreted as integer division, and evaluates to 0 and not 0.09.
You can write 9 / 100.0 instead, or rearrange the expression.
int test = 100 + (100 * (9 / 100));
9/100 = 0
0 * 100 = 0
100 + 0 = 100
you are using integer division so 9 / 100 is zero so test = 100 + 0 = 100
Use Daniel L's answer if you will only be working with expressions that will result in whole integer values. If the values you'll be working with are less clean, use double literals instead of integer literals:
int test = 100.0 + (100.0 * (9.0 / 100.0));
The answer of 9/10 gets truncated to 0, and then you multiply that by 100, and then add 100 to it.
Change:
int test = 100 + (100 * (9 / 100));
to
int test = (int)(100 + (100 * (9 / 100.0)));
and see if it works as expected.
EDIT: wow. Lots of answers while I was typing. Most of them will work, too.
You should be using floating point arithmetic so 9/100 becomes 0.09.
int test = 100.0 + (100.0 * 9.0 / 100.0);
You are using integers for your variable types, so the inner most expression (9 / 100) will result in a 0. Then the next expression would be 100 * 0, which is 0, and finally 100 + 0...
To get your desired result try using float instead:
float test = 100.0 + (100.0 * (9.0 / 100.0));
printf("result: %0.2f\n", test);
Related
I need to convert and round F to C. My function is simply:
return (int)((((float)5 / (float)9) * (f - 32)) + 0.5)
But if I input 14 f, I get back -9 c, instead of -10 c.
C has a nice function lround() to round and convert to an integer.
The lround and llround functions round their argument to the nearest integer value, rounding halfway cases away from zero, regardless of the current rounding direction. C11dr ยง7.12.9.7 2
#include <math.h>
return lround(5.0/9.0 * (f - 32));
The +0.5 and than cast to int has various troubles with it. It "rounds" incorrectly for negative values and rounds incorrectly for various edge case when x +0.5 is not exact.
Use the <math.h> round functions, rint(), round(), nearbyint(), etc) best tools in the shed.
OP comment about needing a vxWorks solution. That apparently has iround to do the job.
For a no math.h nor double solution:
Use (a + sign(a)*b/2)/b idiom. After offsetting by 32 degrees F, we need c = irounded(5*f/9) or c = irounded(10*f/18).
int FtoC(int f) {
f -= 32;
if (f < 0) {
return (2*5*f - 9)/(2*9);
}
return (2*5*f + 9)/(2*9);
}
((14 - 32) * 5.0) / 9.0 = -10.0
-10.0 + 0.5 = -9.5
(int)(-9.5) = -9
Adding 0.5 for rounding purposes will only work when the result of the calculation of f - 32 is positive. If the result is negative, it has to be changed to -0.5.
You could change your code to this:
int roundVal = (f < 32) ? -0.5 : 0.5;
return (int)((((float)5 / (float)9) * (f - 32)) + roundVal);
It sounds like you have two problems:
The number you're trying to round is negative, meaning that the standard trick of adding 0.5 goes the wrong way.
Standard rounding functions like round() are for some reason denied to you.
So just write your own:
double my_round(double x, double to_nearest)
{
if(x >= 0)
return (int)(x / to_nearest + 0.5) * to_nearest;
else
return (int)(x / to_nearest - 0.5) * to_nearest;
}
Now you can write
return (int)my_round(5./9. * (f - 32), 1.0);
Everyone's
"Int() doesn't function correctly in the negative region of the number
line"
is completely and utterly WRONG, and quite disgusting! We programmers should know and understand the concept of "the number line"!
Int(9.5) == 10 => true
Int(-9.5) == -9 => true
Lets say we have a dataset, that coincidently is something point 5, and is a linear system.
Keep in mind that this is matlab syntax, to me programming is programming, so entirely applicable in any language.
x = [-9.5:1:9.5] % -9.5 to 9.5 at increments of 1
-9.5 -8.5 -7.5 ..... 9.5
% Now we need a function Int(), and lets say it rounds to the nearest,
% as y'all say it should be: "direction of the sign". MATLAB doesn't
% have
Int()... that I know of.
function INTEGER = Int_stupid(NUMBER)
POL = NUMBER / abs(NUMBER) % Polarity multiplier
VALUE_temp = NUMBER + (POL * 0.5) % incorrectly implemented
% rounding to the nearest
% A number divided by it's absolute value is 1 times it's
% polarity
% ( -9.5 / abs( -9.5 ) ) = -1
% ( 9.5 / abs( 9.5 ) ) = 1
end
function INTEGER = Int(NUMBER) % how every other Int function works
VALUE_temp = NUMBER + 0.5 % correctly implemented rounding
% to the nearest
end
% Now we need the whole dataset rounded to the "nearest direction of the sign"
x_rounded = Int_stupid(x) => x = [-10, -9, -8,... -1, 1, 2...]
% notice how there is no 0, there is
% discontinuity in this bad rounding.
% Notice that in the plot there is a zig,
% or zag, in my PERFECT LINEAR SYSTEM.
% Notice the two parallel lines with no
% defects representing the RAW linear
% system, and the parallel correctly
% rounded => floor( x + 0.5 )
Rounded to the nearest data, if done correctly, will parallel the actual data.
Sorry for my anger, and programmatic insults. I expect experts to be experts, that don't sell completely incorrect information. And if I do the same, I expect the same humiliation from my peers => YOU.
References ( for 2nd grade how to round numbers ):
%_https://math.stackexchange.com/questions/3448/rules-for-rounding-positive-and-negative-numbers
%_https://en.wikipedia.org/wiki/IEEE_754#Rounding_algorithms
Absolute beginner programmer and wondered if you could help me understand some results and terms. I'm trying to follow the programs logic and how it works out certain values. The following case is an example to try and understand these concepts.
#include <stdio.h>
void main ()
{
int inum = 11;
double dnum = 2.56;
double dec_result;
int int_result;
dec_result = inum / 4 + (3.0 * inum) / 5;
printf("value in dec_result is %.2f\n", dec_result);
dec_result = (double) inum / 4 + (3 * inum) / 5;
printf("value in dec_result is %.2f\n", dec_result);
int_result = (int) dnum * 10 + 1;
printf("value in int_result is %d\n", int_result);
int_result = (int) (dnum * 10 + 1);
printf("value in int_result is %d\n", int_result);
}
I know the results as I've run it through Visual Basic. What I'm struggling to follow is how it works it out.
My workings:
inum and dnum I presume are 'names for values' and could be used interchangeably with say x or y. Same with int_result and dec_result.
First dec_result is 8.60
dec_result = inum / 4 + (3.0 * inum) / 5;
11 (an integer) / 4 + (3.0 * 11) / 5
11 (an integer) / 4 + (33.0) / 5
Then I'm a bit lost... 2.75 + 6.6?
Somehow, due to inum being an integer, value is truncated if written as fraction. But as remaining inum in the brackets is multiplied first then it becomes a decimal place number?
It's displayed as decimal places as specified by the placeholder and specified by data type double.
Second dec_result is 8.75
dec_result = (double) inum / 4 + ( 3 * inum) / 5;
= as double is a cast operator you change inum from int to double, so therefore:
= (double) inum / 4 + (33) / 5;
Then = inum/4 becomes 2.75 + 33/5
Why does the 33/5 bit become 6?
It's displayed as decimal places as specified by the placeholder and specified by data type double.
int_result = (int) dnum * 10 + 1;
= cast operator alters dnum a double to integer so 2.56 becomes 2
= 2 * 10 + 1
= 20 + 1
= 21
should be an integer as specified before the bracket and also %d placeholder means to provide the value as number with no decimal point.
int_result = (int) (dnum * 10 + 1);
I got:
= (int) (2.56 * 10 + 1)
= (int) (25.6 + 1)
= (int) (26.6)
= 26
because the value should be an integer as specified before the bracket and also %d placeholder means to provide the value as number with no decimal point.
Is my logic correct?
The C compiler will do integer arithmetic only if both operands are integers (integer / integer, integer + integer, etc.), otherwise it will do floating point arithmetic (double / integer, double + integer, etc.)
First result:
11 (an integer) / 4 + (33.0) / 5
The first part (11/4) is computed with integer arithmetic, so the answer is 2
The second part (33.0 / 5) is computed with floating point arithmetic, so the answer is 6.6 and the sum is 8.6
Second result:
(double) inum / 4 + (33) / 5;
"(double) inum / 4" is computed using floating point arithmetic, so the answer is 2.75.
"33 / 5" is computed using integer arithmetic, so the answer is 6, and the sum is 8.75
In the following:
int_result = (int) dnum * 10 + 1;
The variable dnum is first cast to an integer, so integer arithmetic is used: 2 * 10 + 1 == 21
And finally:
int_result = (int) (dnum * 10 + 1);
In this case, "dnum * 10 + 1" is computed first, which is done using floating point arithmetic: 2.56 * 10 + 1 == 26.6. Then the cast - (int) - truncates to give 26.
When an arithmetic operator is given two integer arguments, the result is an integers, so any fraction is discarded. So11 / 4is2, not2.75`. But when you combine an integer with a floating point, the integer is first converted to floating point, and a floating point result is returned.
As a result:
dec_result = inum / 4 + (3.0 * inum) / 5;
= 11 / 4 + (3.0 * 11) / 5
= 11 / 4 + (3.0 * 11.0) / 5
= 2 + 33.0 / 5
= 2 + 6.6
= 8.6
This question already has answers here:
Why does division result in zero instead of a decimal?
(5 answers)
Closed 7 years ago.
Why does this expression give me an output of zero?
float x = ((1000)/(24 * 60 * 60));
Breaking this into two parts, gives the correct result:
float x = (1000);
x /= (24 * 60 * 60);
The statement
float x = ((1000)/(24 * 60 * 60));
does the following:
Declares a variable x of type float.
Evaluates ((1000)/(24 * 60 * 60)).
Evaluates 24*60*60 which is 86400.
Evaluates 1000/86400 which is 0.
Assigns the result of that (which is 0) to x.
In the second step, ((1000)/(24 * 60 * 60)) is zero - the division is integer division, because both operands are integers. The fact that the result gets assigned to a floating point variable later makes no difference.
The simplest fix is to make sure either side of the division is a floating-point number, so it will use floating-point division. For example, you could change 1000 to 1000.0f.
See this answer, it will give you the correct output
#include <stdio.h>
int main(void) {
float x = (float)1000/(24 * 60 * 60);
printf("%f",x);
return 0;
}
Output: 0.011574
Output can also be seen: http://ideone.com/6bMp9r
I am writing a program in C that calculates this formula:
(source: crewtonramoneshouseofmath.com)
here is the line of code (I am just using + instead of the +-):
x = ((-1 * b) + (sqrt(pow(b, 2) - 4 * a * c)))/(4 * a);
I am not getting the correct root. For example if a = 1, b=-2, and c=-2 it SHOULD be 2.73. Instead I am getting 1.37.
Been staring at the code and I don't see the mistake. Can someone point it out for me?
x = (...) / (4 * a)
Shouldn't this be 2 * a?
It's interesting that 1.37 (what you're getting) is about half of 2.73 (what you want) and, lo and behold, there it is in your denominator, dividing by 4a instead of 2a.
Personally, I would write that expression as:
x = (-b + sqrt (b * b - 4 * a * c)) / (2 * a);
since it more closely matches the equation you're trying to duplicate (the -1 * b is better expressed as -b) and I find calling pow to get a simple square to be unnecessary where b * b does the same job without a function call.
x1 = ((-1 * bcoeff) + (sqrt(pow(bcoeff, 2) - 4 * acoeff * ccoeff)))/(2 * acoeff);
Check yourself here: .../(4 * acoeff)
While this question has already been answered and your error pointed out. I would just like to mention that breaking the problem down into more lines would increase its readability and potentially reduce mistakes made.
float den = 2 * a;
float num1 = (-1 * b);
float num2 = pow(b ,2) - (4 * a * c);
float x = (num1 + sqrt(num2))/ den;
I'm using two different variable to divide in the calculation with the variable from int and double. These work fine when I use something like:
int cost
cost = 40;
cost = (cost / 400) * 20 * 2;
For this the method works fine and I get the right result which is 4, but when I use the variable cost and put it in the header instead, like:
#define cost 40
int total_cost;
total_cost = (cost / 400) * 20 * 2;
this always results in 0 for me and I don't know why. Even if I use printf with %d or %f this still gives me a result of 0.
You are doing integer division - which rounds down.
Therefore:
cost / 400
is returning zero because cost = 40 and 40 / 400 rounds down to zero.
What you should do is use a floating-point type like double.
EDIT:
double cost
cost = 40;
cost = (cost / 400) * 20 * 2;
and
#define cost 40
double total_cost;
total_cost = ((double)cost / 400) * 20 * 2;
Order of operations, and Integer Division.
Integer Division always truncates. Mathematically, 40/400 = .1 - but that's not an integer. The remainder is thrown away, leaving you with: 40 / 400 = 0.
Order of operations means that the division is done first, in your example. Since the order of multiplication and division doesn't matter too much (mathematically speaking), try changing the order:
total_cost = cost * 20 * 2 / 400;
Multiplication happens first, division last, giving you:
40 * 20 * 2 / 400 = 800 * 2 / 400 = 1600 / 400 = 4