|
发表于 2017-9-9 16:18:09
|
显示全部楼层
// 鱼C92.cpp : Defines the entry point for the console application.
//
/*
1, 2, 4, 8, 16, 32, 64, 128这8个数字利用加法可以得到1~255中的任意数字
如 21 = 1 + 4 + 16; 192 = 64 + 128;
编写一个函数输入1~255的数字,给出如何利用1, 2, 4, 8, 16, 32, 64, 128的
加法可以得到这个数字
*/
/*本人小白,学c语言不久,给出的答案可能不完美,轻喷,另求指正*/
#include "stdafx.h"
#include <stdio.h>
void ret (int x, int y)//计算结果
{
int rem; //余数
//int a[8] = {0};
printf("%d = ", x);
rem = x % y;
printf(" %d", y);
y /= 2;
do
{
if (rem < y)
{
y /= 2;
}
else
{
rem %= y;
printf(" + %d", y);
y /= 2;
}
}while(rem);
}
//void ret (int x, int rem);
int main(int argc, char* argv[])
{
int n = 0;
int b[8] = {1, 2, 4, 8, 16, 32, 64, 128};
int t = 0;
puts("请输入一个1~255之间的数字,1, 2, 4, 8, 16, 32, 64, 128这8个数字除外");
scanf("%d", &n);
for(int i = 0; i < 8; ++i)//对数组b进行遍历,排除用户输入的非法数字
{
if (n == b[i])
t = 1;
}
if(t)
{
printf("%d无法利用1, 2, 4, 8, 16, 32, 64, 128这8个数字加法得到\n", n);
}
else
{
if (n < 4)
{
ret (n, 2);
printf("\n");
}
else if (n < 8)
{
ret (n, 4);
printf("\n");
}
else if(n < 16)
{
ret (n, 8);
printf("\n");
}
else if (n < 32)
{
ret (n, 16);
printf("\n");
}
else if (n < 64)
{
ret (n, 32);
printf("\n");
}
else if (n < 128)
{
ret (n, 64);
printf("\n");
}
else if (n <= 255)
{
ret (n, 128);
printf("\n");
}
}
return 0;
}
|
评分
-
查看全部评分
|