A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© D.man 中级黑马   /  2015-3-27 09:01  /  807 人查看  /  7 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

编译通过了,但是运行就出问题了。。。。。情境模拟是这样的:将一张厚度0.01米的纸不断对折,问几次后纸的高度为8848米?(早上看到一位朋友在论坛有询问,结果自己写的运行有问题),代码如下:
class Test_2
{
        public int func(int i)
                {
                        if(i == 1)
                                return 2;
                        else
                                return func(i-1);
                }
       
        public static void main(String[] args)
        {
                double sum = 0.00;
                int count;
                Test_2 t = new Test_2();
               

                for(count=1; sum < 8848 ;count++)
                {       
                        sum = t.func(count)*0.01;
                }
                System.out.println("需要进行"+count+"次");
        }
}

7 个回复

倒序浏览
  1. public class Test_2 {
  2.         public int func(int i) {
  3.                 if (i == 1)
  4.                         return 2;
  5.                 else
  6.                         return func(i - 1);//这里调用递归? 无法理解
  7.                 //递归这么调用那这里无论传过来的数字是多少,永远都只可能返回2
  8.         }

  9.         public static void main(String[] args) {
  10.                 double sum = 0.00;
  11.                 int count;
  12.                 Test_2 t = new Test_2();

  13.                 for (count = 1; sum < 8848; count++) {
  14.                         // 这里sum一直被不停的赋值,由于t.func只可能返回2,所以 sum 不停的被赋值0.02
  15.                         // 永远满足不了条件,for循环就会无限循环下去.
  16.                         sum = t.func(count) * 0.01;
  17.                 }
  18.                 System.out.println("需要进行" + count + "次");
  19.         }
  20. }
复制代码


思路有问题
回复 使用道具 举报

thank you!知道错在哪里了,想算2的阶乘的,原来是递归错了。
回复 使用道具 举报
都解决了,来看看
回复 使用道具 举报
将代码修改如下,就搞定了,感觉思路上好像走了很大弯路,先这样吧。
class Test_2
{
        //2的乘方运算
        public int func(int i)
        {
                int sum = 1;
                for(int x = 1;x <= i;x++)
                        sum *= 2;
                return sum;
        }
       
        public static void main(String[] args)
        {
                double sum = 0.00;
                int count;
                Test_2 t = new Test_2();
               
                //计算高度值
                for(count=1; sum < 8848 ;count++)
                {       
                        sum = t.func(count)*0.01;
                }
                count--;//因为计数器从1开始计数,所以要-1;
                System.out.println("需要进行"+count+"次");
        }
}
回复 使用道具 举报
涨知识了!
回复 使用道具 举报
Grady 中级黑马 2015-3-27 21:32:16
7#
加油      
回复 使用道具 举报
佐佑 中级黑马 2015-3-27 21:37:09
8#
提示慢慢调就是了啊
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马