划分直到达到一定数量并存储循环划分的次数

如果将 1 除以 2,则得到 0.5。如果你再除以 2,你会得到 0.25。编写一个程序,计算并输出 1 除以 2 所需的次数,才能得到小于万分之一 (0.0001) 的值。


我有一个应该可以工作的 for 循环,但它没有返回任何结果


公共类主要{


public static void main(String[] args) {

    double count ;

    for(double i = 1; i<= 0.0001; count++){

            count = i/2;



        System.out.println("You have to divide 1 " + count + "times to get 0.0001");



    }

程序运行它只是不返回任何内容。


www说
浏览 189回答 4
4回答

森栏

尝试这个&nbsp; &nbsp; int count = 0;&nbsp; &nbsp; double i = 1;&nbsp; &nbsp; while(i >= 0.0001){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i = i/2;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; count++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("You have to divide 1 " + count + " times to get 0.0001");&nbsp; &nbsp; }也许你只想在循环之后打印出来在 count 的值从未被用来评估循环之前。尝试有两个变量。

隔江千里

好吧,我明白了,只需围绕 public class Main { 切换一些东西public static void main(String[] args) {&nbsp; &nbsp; int count = 0;&nbsp; &nbsp; for (double i = 1; i >= 0.0001; count++ ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;i = i / 2;&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println("You have to divide 1 " + count + " times to get 0.0001");

狐的传说

您可以使用下面的代码。&nbsp; &nbsp; &nbsp; &nbsp; int count = 0;&nbsp; &nbsp; &nbsp; &nbsp; for(double i = 1; i>= 0.0001; ){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i = i/2;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;count++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("You have to divide 1 " + count + " times to get " + i);&nbsp; &nbsp; &nbsp; &nbsp; }

慕虎7371278

您可以翻译您的等式:x / y^n <= z到n >= log(x/z) / log(y)因此它很简单:public static void main(String[] args) {&nbsp; &nbsp;System.out.println("You have to divide 1 " + Math.ceil(Math.log(1.0 / 0.0001) / Math.log(2)) + " times by 2 to get 0.0001");}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java