![]() |
Rounding numbers
Wow..ima complete n00b at programming!! i should noe this by now!
ok i sorta learned java.. cant really remember how to round in java... and im not sure if i should look for my java book and try to find out to round because im not sure if its the same in C.. Does any1 noe what the command is?? plz and thxs:) |
Re: Rounding numbers
You can use the Math.round() method. Below is the two definitions of the method.
Code:
public static int round(float a) |
Re: Rounding numbers
Usually when I want to round I just use some integer math. It can be kind of ugly but most of the times it works well and I do not have to memorize function calls. When you convert a floating point number to an int it will always round down so if you add .5 to a float then convert to an integer it will be rounded correctly.
float num = 1.5f; int rounded = (int)(num+.5) But anyway using a round function is probably better style... |
Re: Rounding numbers
Quote:
|
Re: Rounding numbers
I made a comment in your other thread, but you may want to check out the discussion on float variables. They aren't the best choice for the RC hardware.
|
Re: Rounding numbers
The problem with using a cast when trying to round is that all it does is remove the bits holding the decimal part of the number, this is not equivalent to rounding.
double number = 12.8743; int val; val = (int) number; val now equals 12 ... clearly not the result you want. You could use math.Round or just write your own function public int round(double val) { if(val-(int)val>=.5) { return (int)val+1; } else { return (int)val; } } |
Re: Rounding numbers
Quote:
math.Round is a java comand...doesnt work in C :( |
Re: Rounding numbers
Quote:
Quote:
|
Re: Rounding numbers
Quote:
my code: int i = 1; static int time_i; i=i+1; // This will increment 'i' by the value 1 every loop time_i = ((i * 262) / 10000); But thats going to caculate a floating number... i would just like a rounded integer from that sorta type of logic.... srry if i seem confusing.... |
Re: Rounding numbers
Ohh I see. Actually, this line:
Code:
time_i = ((i * 262) / 10000);So after that line above, time_i is assigned 0 until i > 38 (i*262/10000 = i*0.0262 < 1, but since we have an integer it truncates the decimal part and gives you 0). For 38 <= i <= 76, time_i will be assigned 1 (you will have 1.***, and the decimal part will be removed). For 77 <= i <= 152, time_i = 2, and so on. |
Re: Rounding numbers
Quote:
|
Re: Rounding numbers
Quote:
Code:
static int i = 1;...at least until 125 loops have occurred, after a bit more than 3.25 seconds, after which time (i * 262) will overflow and you'll start getting negative results. |
Re: Rounding numbers
Quote:
|
Re: Rounding numbers
A few notes:
Also, I find a series of typedef's helpful: Code:
typedef signed char SCHAR; |
| All times are GMT -5. The time now is 01:20. |
Powered by vBulletin® Version 3.6.4
Copyright ©2000 - 2017, Jelsoft Enterprises Ltd.
Copyright © Chief Delphi