有人能告诉我为什么我的Java While Loop没有正常退出吗?

时间:2014-03-21 02:39:45

标签: java

好的,所以我的循环按预期工作,但似乎没有退出循环。我确定了这一点,因为在我调用此函数的行之后,我的main函数中没有执行任何操作

        public static void Simulator(int N){
    double x=0.01;
    int t=0;
    System.out.println(x);
    while(t<=N){
        x=3.5*x*(1-x);
        System.out.println(x);
        t=t+1;
        System.out.println(t);
    }

2 个答案:

答案 0 :(得分:1)

我编写并测试了您通过制作示例程序(其中N = 10未传入)所提供的代码示例:

public static void main(String[] args) {
    int t = 0;
    int N = 10;
    double x = 0.01;

    while (t <= N) {
        x = 3.5 * x * (1 - x);
        System.out.println(x);
        t = t + 1;
        System.out.println(t);
    }
}

输出符合预期:

0.03465
1
0.11707282125
2
0.36178371521097946
3
0.8081369051669213
4
0.5426807668595311
5
0.8686242324909882
6
0.3994066132715046
7 
0.8395833969127198
8
0.4713909078942638
9
0.8721353194710993
10
0.3903035640074999
11

由此可以得出结论,在主循环执行并正常退出时,它必须是主方法中的其他东西导致问题。

检查您是否在主方法中正确调用Simulator方法。

干杯

答案 1 :(得分:0)

循环工作正常。我不知道你之后做了什么,但它会进入内部,而N + 1次。

此外,您应该考虑使用for:

for(int t=0; t <= N; t++)
{
    x=3.5*x*(1-x);
}