问题描述:
一群猴子摘了一堆桃子,他们每天都吃当前桃子的一半且再多吃一个,到了第十天就只剩余一个桃子,用多种方法求出这只猴子原来共摘了多少桃子。
解题思路:
代码如下:
#include<stdio.h> //scanf printf
#include<stdlib.h> //system
#include<math.h> //pow
int main()
{
system("mode con cols=100 lines=100");
system("color 0A");
int num_left; //桃子剩余个数
int times; //吃桃子个数
int total; //摘得桃子总数
int flag1 = 1;//状态标志位
int flag2 = 1;//状态标志位
while(flag1) //输入正确的话(输入正数)退出while循环,否则一直执行
{
printf("please input the number of peachs left:\n");
scanf("%d",&num_left);
if(num_left > 0)
{
flag1 = 0;
}
else
{
printf("input error,please input again!\n");
}
}
while(flag2)//输入正确的话(输入正数)退出while循环,否则一直执行
{
printf("please input the eating times:\n");
scanf("%d",×);
if(times > 0)
{
flag2 = 0;
}
else
{
printf("input error,please input again!\n");
}
}
total = pow(2,times) * (num_left + 2) - 2;
printf("the total number of peaches is %d:\n",total);
system("pause");
return 0;
}
或者不用状态标志位:
#include<stdio.h> //scanf printf
#include<stdlib.h> //system
#include<math.h> //pow
int main()
{
system("mode con cols=100 lines=100");
system("color 0A");
int num_left; //桃子剩余个数
int times; //吃桃子个数
int total; //摘得桃子总数
while(1) //输入正确的话(输入正数)退出while循环,否则一直执行
{
printf("please input the number of peachs left:\n");
scanf("%d",&num_left);
if(num_left > 0)
{
break;
}
else
{
printf("input error,please input again!\n");
}
}
while(1)//输入正确的话(输入正数)退出while循环,否则一直执行
{
printf("please input the eating times:\n");
scanf("%d",×);
if(times > 0)
{
break;
}
else
{
printf("input error,please input again!\n");
}
}
total = pow(2,times) * (num_left + 2) - 2;
printf("the total number of peaches is %d:\n",total);
system("pause");
return 0;
}虽然把问题解决了可是,是不是觉得解题过程太麻烦,是不是有其他更简便的方法呢,对!逆向思维:即从问题的结果倒推出最初的状态!
#include<stdio.h> //scanf printf
#include<stdlib.h> //system
int main()
{
system("mode con cols=100 lines=100");
system("color 0A");
int times = 0; //记录猴子数桃子之前吃桃子的次数
int total = 0; //摘得桃子总数
while(true) //输入正确的话(输入正数)退出while循环,否则一直执行
{
printf("please input the number of peachs left:\n");
scanf("%d",&total);
if(total > 0)
{
break;
}
else
{
printf("input error,please input again!\n");
continue;
}
}
while(true)//输入正确的话(输入正数)退出while循环,否则一直执行
{
printf("please input the eating times:\n");
scanf("%d",×);
if(times > 0)
{
break;
}
else
{
printf("input error,please input again!\n");
continue;
}
}
while(times > 0) //逆向求桃子总数
{
total = 2 * (total + 1);//上一次桃子总数
times--;
}
printf("the total number of peaches is %d:\n",total);
system("pause");
return 0;
}
原文地址:http://blog.csdn.net/zongyinhu/article/details/44998513