Floating-Point Math के लिए bc
Bash सिर्फ whole numbers count कर सकता है, एक kid की तरह जो सिर्फ apples जानता है, half apples नहीं। bc वह friend है जो decimals समझता है, इसलिए आप sum उसे hand कर देते हैं।
In this page:
Syntax
result=$(echo "expression" | bc -l)
bc for Floating-Point Math
Bash arithmetic सिर्फ integers handle करता है, इसलिए bc (basic calculator) उपयोग होता है जब आपको decimal precision चाहिए।
आप आमतौर पर एक expression string इसमें pipe करते हैं, जैसे echo "10 / 3" | bc -l, जहां -l ज़्यादा precision वाली एक math library load करता है। यह shell scripts में floating-point calculations के लिए standard workaround है।
Note:
Decimal results चाहिए, सिर्फ truncated integers नहीं, तो हमेशा plain
bc के बजाय bc -l उपयोग करें।उदाहरण: bc for Floating-Point Math
#!/bin/bash
result=$(echo "10 / 3" | bc -l)
echo "10 / 3 = $result"
result=$(echo "scale=2; 22/7" | bc -l)
echo "22 / 7 (2 decimal places) = $result"
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- Decimals के लिए
$(( ))उपयोग करना, जो integers में truncate हो जाता है। scale=भूल जाना, इसलिएecho "10/3" | bc3print करता है।bcinstall करना भूल जाना, जो हर minimal system पर मौजूद नहीं होता।
🔒
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: