|
|
|
![]() |
|
|||||||
|
||||||||
![]() |
|
|
Thread Tools | Rate Thread | Display Modes |
|
|
|
#1
|
||||
|
||||
|
Re: How does division work?
If you add 0.5, it will "round" to the nearest integer:
int x = (int)(40/9 + 0.5); // 40/9 = 4.444 repeating and rounds down to 4 int y = (int)(40/6 + 0.5); // 40/6 = 6.666 repeating, rounds up to 7 |
|
#2
|
|||
|
|||
|
Re: How does division work?
Quote:
Code:
174: var1 = (int)((40/6)+0.5); 04464 0E06 MOVLW 0x6 << compiler gens 6 04466 0101 MOVLB 0x1 04468 6FE6 MOVWF 0xe6, BANKED 0446A 6BE7 CLRF 0xe7, BANKED Code:
175: var1 = (int)((40+(6/2))/6); 0446C 0E07 MOVLW 0x7 << compiler gens 7 0446E 6FE6 MOVWF 0xe6, BANKED 04470 6BE7 CLRF 0xe7, BANKED If you try this with variables in the formula instead of constants, then the compiler can't figure out the answer at compile-time and generates the necessary code to figure this out at run-time. Adding 0.5 may cause conversion into and out of floating point which are really slow operations. A more correct integer based answer would be: Code:
var1 = ((var2*10)+(divisor*10)/2))/(divisor*10); However, in the case of an odd divisor such as 9, the remainder can only be 4 or 5 - not 4.5. So this suggests the simplier form below of should yield the correct answer: Code:
var1 = ((var2+(divisor/2)) / divisor; (40+(9/2)) / 9 = 44 / 9 = 4 (40+(6/2)) / 6 = 43 / 6 = 7 or did I mess up... again... Last edited by dcbrown : 09-01-2008 at 10:46. |
|
#3
|
||||
|
||||
|
Re: How does division work?
Quote:
Instead, what you can try (for your example) is the following: int x = (int)(40.0/9.0 + 0.5); // 40/9 = 4.444 repeating and rounds down to 4 int y = (int)(40.0/6.0 + 0.5); // 40/6 = 6.666 repeating, rounds up to 7 by adding the ".0" to the divisor and the dividend, you turn the division into a floating point operation, instead of an integer operation. That means that it won't truncate the result of the division, only the final result of the equation as you stick it into an integer. To accomplish this using variables instead of straight numbers, by far the easiest way is to typecast the variables: int x = (int)(((float)dividend)/((float)divisor) + 0.5); That tells the compiler that, for this one instance, you want it to treat the variables as floats instead of integers, meaning that it won't truncate any results in mid-computation. |
![]() |
| Thread Tools | |
| Display Modes | Rate This Thread |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| How does it work? | Ryan O | Control System | 5 | 12-03-2006 19:15 |
| How does Nationals work? | coldfusion1279 | Championship Event | 29 | 30-03-2005 16:47 |
| How Does a Winch Work? | Aaron Lussier | Technical Discussion | 23 | 20-01-2004 21:14 |
| how does crab drive work? | Soukup | Technical Discussion | 13 | 25-04-2003 11:31 |
| How does Nationals work?? | LunchBox | Championship Event | 16 | 18-03-2003 15:55 |