十进制数转二进制(字符串实现)

初始版

#include <stdio.h>
#include <string.h>
#include <assert.h>
int ascii_to_integer(char *str)
{
	int n = 0;
	assert(str);
	while (*str != '\0')
	{
		while (*str >= '0' && *str <= '9')//判断字符串是否全为数字
		{
			n = n * 10 + (*str - '0');//ASCII码值差即为数字
			str++;
		}
		return n;
	}
	return 0;
}
int main()
{
	char c[100];
	int a[100] = { 0 };
	int i,j;
	while (1)
	{
		printf("请输入数字:");
		gets_s(c);
		if (c[0] == '-')
		{
			printf("该数为负数,请重新输入!\n"); continue;
		}
		for (i = 0; (c[i] != '\0') && i <= 99; i++)
		{
			if (c[i] == '.')
			{
				printf("该数为小数,请重新输入!\n"); break; 
			}
		}
		if (c[i] == '.')
		 continue;
		else
		break;
	}
	//printf("该数为整数。\n");
	j = ascii_to_integer(c);
	for (i=0;j != 0;i++)
	{
		a[i] = j % 2;
		j = j / 2;
	}
	for (i--; i >= 0; i--)
	{
		printf("%d",a[i]);
	}
		return 0;
}

改进版

排除任意非法字符

#include <stdio.h>
#include <string.h>
int main()
{
	char c[100];
	int a[100] = { 0 };
	int i,j;
	while (c[i] != '\0') 
	{
		printf("请输入整数:");
		gets_s(c);
		for (i = 0,j = 0; c[i] != '\0'; i++)
		{
			if (c[i] >= '0'&&c[i] <= '9')
				j = j * 10 + (c[i] - '0');
			else
			{
				printf("输入有误,请重新输入。\n");
				break;
			}
		}
	}
	for (i=0;j != 0;i++)
	{
		a[i] = j % 2;
		j = j / 2;
	}
	for (i--; i >= 0; i--)
	{
		printf("%d",a[i]);
	}
		return 0;
}

发布了2 篇原创文章 · 获赞 2 · 访问量 166

猜你喜欢

转载自blog.csdn.net/qq_43207846/article/details/104603871
今日推荐