十进制转二进制的基本方法是 不断除以2,然后倒序拼接余数。以下是一个简单的Python实现:
```python
def decimal_to_binary(decimal_num):
if decimal_num == 0:
return "0"
binary = ""
num = abs(decimal_num) 处理负数情况
while num > 0:
binary = str(num % 2) + binary 取余数并拼接
num = num // 2
return "-" + binary if decimal_num < 0 else binary
测试
print(decimal_to_binary(10)) 输出:1010
print(decimal_to_binary(-10)) 输出:-1010
print(decimal_to_binary(0)) 输出:0
```
这个函数首先检查输入的十进制数是否为0,如果是,则直接返回"0"。然后,它取输入数的绝对值,并在循环中不断除以2,将余数拼接到结果字符串的前面。最后,如果输入的数是负数,则在结果字符串前加上负号。
其他编程语言的实现
Java
```java
public class DecimalToBinary {
public static String decimalToBinary(int decimalNum) {
if (decimalNum == 0) {
return "0";
}
StringBuilder binary = new StringBuilder();
int num = Math.abs(decimalNum);
while (num > 0) {
binary.insert(0, num % 2);
num /= 2;
}
return decimalNum < 0 ? "-" + binary.toString() : binary.toString();
}
public static void main(String[] args) {
System.out.println(decimalToBinary(10)); // 输出:1010
System.out.println(decimalToBinary(-10)); // 输出:-1010
System.out.println(decimalToBinary(0)); // 输出:0
}
}
```
C++
```cpp
include include include std::string decimalToBinary(int decimalNum) { if (decimalNum == 0) { return "0"; } std::string binary = ""; int num = std::abs(decimalNum); while (num > 0) { binary = std::to_string(num % 2) + binary; num /= 2; } return decimalNum < 0 ? "-" + binary : binary; } int main() { std::cout << decimalToBinary(10) << std::endl; // 输出:1010 std::cout << decimalToBinary(-10) << std::endl; // 输出:-1010 std::cout << decimalToBinary(0) << std::endl; // 输出:0 return 0; } ``` C ```csharp using System; class DecimalToBinary { public static string DecimalToBinary(int decimalNum) { if (decimalNum == 0) { return "0"; } string binary = ""; int num = Math.Abs(decimalNum); while (num > 0) { binary = (num % 2).ToString() + binary; num /= 2; } return decimalNum < 0 ? "-" + binary : binary; } public static void Main() { Console.WriteLine(DecimalToBinary(10)); // 输出:1010 Console.WriteLine(DecimalToBinary(-10)); // 输出:-1010 Console.WriteLine(DecimalToBinary(0)); // 输出:0 } } ``` 这些代码示例展示了如何在不同的编程语言中实现十进制到二进制的转换。基本思路是相同的:不断除以2,将余数倒序拼接成字符串。