Home > Software design >  I always get the same result for sf
I always get the same result for sf

Time:03-01

    public void berechne2() {
        float sf=16_777_220f;
        System.out.println("sf vorher = "   sf);
        int n=100;
        int d=1;
        for(int k=1; k<=n;k  ) {
            sf=sf d;
        }
        System.out.println("sf nachher = "   sf);
    }   

}

Why do i get always same values for sf? I want to get sf the numbers from 1 to 100.

CodePudding user response:

Not sure why you need a float.

Your code can be greatly simplified to

int sf=16_777_220;
System.out.println("sf vorher = "   sf);
for(int k=1; k<=100;k  ) {
     System.out.println("sf nachher = "   sf  );
}

CodePudding user response:

I'm wondering why you want to use a floating point variable in order to sum up integers… You could use an int or a long instead.

You commented i want to add the numbers from 1 to 100 on sf and print it just once, but that is not what your code is doing. It adds 1 to sf in each iteration to the initial value instead of adding 1 2 ... 100, the numbers from 1 to 100.

You are getting equality due to float as data type as mentioned in a comment. If you used a double, it would produce different values but would still appear pointless for integer values.

Maybe try something like this:

public static void berechne2() {
    // use a data type meant for integers
    long sf = 16_777_220L;
    // print the initial value
    System.out.println("sf vorher  = "   sf);
    // use values in the loop instead of variables
    for (int k = 1; k <= 100; k  ) {
        // add the current value of k to the variable, not just 1
        sf  = k;
    }
    // print the result once
    System.out.println("sf nachher = "   sf);
}

Output:

sf vorher  = 16777220
sf nachher = 16782270
  • Related