mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Created SC2017 (markdown)
21
SC2017.md
Normal file
21
SC2017.md
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
## Increase precision by replacing a/b*c with a*c/b.
|
||||||
|
|
||||||
|
### Problematic code:
|
||||||
|
|
||||||
|
percent=$((count/total*100))
|
||||||
|
|
||||||
|
### Correct code:
|
||||||
|
|
||||||
|
percent=$((count*100/total))
|
||||||
|
|
||||||
|
### Rationale:
|
||||||
|
|
||||||
|
If integer division is performed before multiplication, the intermediate result will be truncated causing a loss of precision.
|
||||||
|
|
||||||
|
In this case, if `count=1` and `total=2`, then the problematic code results in `percent=0`, while the correct code gives `percent=50`.
|
||||||
|
|
||||||
|
### Exceptions:
|
||||||
|
|
||||||
|
If you want and expect truncation you can ignore this message.
|
||||||
|
|
||||||
|
ShellCheck doesn't warn when `b` and `c` are identical expressions, e.g. `a/10*10`, under the assumption that the intent is to rounded to the nearest 10 rather than the no-op of multiply by `1`.
|
Reference in New Issue
Block a user