帮我写一个将十进制转换成二进制数的程序
时间: 2023-03-26 14:03:57 浏览: 73
好的,以下是将十进制数转换为二进制数的程序:
#include <stdio.h>
int main() {
int decimal, binary = , base = 1;
printf("请输入一个十进制数:");
scanf("%d", &decimal);
while (decimal > ) {
binary += (decimal % 2) * base;
decimal /= 2;
base *= 10;
}
printf("二进制数为:%d", binary);
return ;
}
相关问题
java编写一个程序将十进制转换成二进制
可以使用以下代码实现将十进制转换成二进制:
```java
import java.util.Scanner;
public class DecimalToBinary {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入一个十进制数:");
int decimal = input.nextInt();
String binary = "";
while (decimal > 0) {
binary = (decimal % 2) + binary;
decimal /= 2;
}
System.out.println("转换后的二进制数为:" + binary);
}
}
```
该程序首先使用 `Scanner` 类获取用户输入的十进制数,然后使用一个 `while` 循环不断将该数除以 2 并取余,将余数拼接到二进制数的前面,直到十进制数为 0。最后输出转换后的二进制数。
用栈方法写一个将十进制数转换为二进制数的c语言程序
下面是用栈方法写的将十进制数转换为二进制数的 C 语言程序:
```c
#include <stdio.h>
#include <stdlib.h>
#define STACK_SIZE 32 // 栈的最大空间
typedef struct {
int top; // 栈顶指针
int data[STACK_SIZE]; // 栈的数据
} Stack;
// 初始化栈
void initStack(Stack *stack) {
stack->top = -1;
}
// 判断栈是否为空
int isEmptyStack(Stack *stack) {
return stack->top == -1;
}
// 判断栈是否已满
int isFullStack(Stack *stack) {
return stack->top == STACK_SIZE - 1;
}
// 入栈
void pushStack(Stack *stack, int value) {
if (isFullStack(stack)) {
printf("Error: stack is full.\n");
exit(EXIT_FAILURE);
}
stack->top++;
stack->data[stack->top] = value;
}
// 出栈
int popStack(Stack *stack) {
if (isEmptyStack(stack)) {
printf("Error: stack is empty.\n");
exit(EXIT_FAILURE);
}
int value = stack->data[stack->top];
stack->top--;
return value;
}
// 将十进制数转换为二进制数
void decimalToBinary(int decimal) {
Stack stack;
initStack(&stack);
while (decimal > 0) {
int remainder = decimal % 2;
pushStack(&stack, remainder);
decimal /= 2;
}
printf("Binary number: ");
while (!isEmptyStack(&stack)) {
int binary = popStack(&stack);
printf("%d", binary);
}
printf("\n");
}
int main() {
int decimal;
printf("Enter a decimal number: ");
scanf("%d", &decimal);
decimalToBinary(decimal);
return 0;
}
```
该程序定义了一个栈的结构体,实现了栈的基本操作:初始化、判断是否为空、判断是否已满、入栈和出栈。然后定义了一个函数,将十进制数转换为二进制数,具体实现是将十进制数不断除以 2,每次得到的余数入栈,最后依次出栈得到二进制数。在主函数中,输入一个十进制数,调用上述函数进行转换并输出结果。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)