2012-09-13 35 views
0

我有一个从最小值到最大值的范围。 我想通过计算为每个这些值生成一组信息。 我想通过打印输出这些信息。JAVA循环并为条件内的每个值生成输出

如何产生这个输出给定一个循环将只输出一次范围内的一个值的信息?

编程经验 - 绝对初学者。

以下是代码: 基本上,如果用户输入1,我输出所有min2值的信息。 否则,我只输出min2的集合及其probB为1/2的信息。 另外,我可以只使用min1(来自用户输入),而不分配给min2吗?

int prompt = Integer.parseInt(input); // user input 
int min2 = 0; 
double probB = 0; 
for (min2 = min1; min2 < max1; min2++) // for loop 
{ 
    if (prompt==1){ 
    int R = 0; 
    double Rlow = 0; 
    double Rhigh = 0; 
    R = (int) (Math.sqrt(2) + 1)*min2; 
    Rlow = (Math.sqrt(2)+1)*min2+ 1; 
    Rhigh = (Math.sqrt(2)+1)*min2; 
    System.out.println(min2); 
    System.out.print(""+Rlow+""+Rhigh); 
    System.out.println(R); 
    probB = (R/R+min2)*(R-1/R+min2-1); 
    System.out.println(probB); 
    } 
    else { 
    int R = 0; 
    double Rlow = 0; 
    double Rhigh = 0; 
    R = (int) (Math.sqrt(2) + 1)*min2; 
    Rlow = (Math.sqrt(2)+1)*min2+ 1; 
    Rhigh = (Math.sqrt(2)+1)*min2; 
    probB = (R/R+min2)*(R-1/R+min2-1); 

    if (probB == 1/2){ 
     System.out.println(min2); 
     System.out.println(""+Rlow+""+Rhigh); 
     System.out.println(R); 
     System.out.println(probB); 
    } 
    } 
} 
+1

你能告诉我们你现在的代码吗?也许我们可以指出它的错误。 – Mysticial

+0

[for for语句](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html)和[PrintStream](http://docs.oracle.com/javase/7/docs/ api/java/io/PrintStream.html) – user1329572

+1

具体如我可以...基于问题的彻底性:'for(int i = min; i <= max; i ++){System.out.println(计算(ⅰ)); }' –

回答

3

代替

if (probB == 1/2){ 

使用

if (probB == 1.0d/2.0d){ 

表达1/2被计算为的整数,它的值是零。更妙的是:

if (probB == 0.5d){ 

不过请注意,如果有在probB计算任何四舍五入的结果可能不是最终会被恰好为0.5,即使你希望它。由于浮点表示的不准确性,您可以构造表达式,其中最终结果'应该'为0.5,但实际结果非常接近但不是0.5。你最好的选择是做类似的事情:

if (Math.abs(probB-0.5d) <1.0e-10d) 

也就是说,接近于10^10中的一部分

浮点计算非常有用,但由于它们不是精确表示这一事实,它们带有一些问题。在十进制中,有一整组的有理数不能准确地表示,如1/3,1/7等。通过扩展位数(0.33333333 ...或0.142857142857142 ...)可以任意关闭。但是不能用十进制编写精确的表示法。同样的事情发生在浮点数上(对于不同的数字集合),但FP的长度是固定的,所以像0.1这样的数字不能准确地表达在FP中。它很接近,但并不确切。您必须始终考虑这种可能性进行比较。