当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Float sum()用法及代码示例


Java Float 类的 sum() 方法返回两个浮点参数的总和,与 '+' 运算符执行的操作相同。

用法:

public static float sum(float a, float b)

参数:

  • 指定传递的第一个参数
  • 指定传递的第二个参数

返回值:

sum() 方法返回表示 a 和 b 之和的浮点数。

例子1

public class FloatSumExample1 {
    public static void main(String[] args) {
        Float f1 = 562.827f;
        Float f2 = 900.981f;
        // returns the sum of f1 and f2
        Float f3 = Float.sum(f1,f2);
        System.out.println("Number I = "+f1);
        System.out.println("Number II = "+f2);
        System.out.println("{Sum of two numbers = "+f3);
        System.out.println();
        //passing negative number
        Float f4 = -7367.76f;
        System.out.println("Number III = "+f4);
        Float f5 = Float.sum(f3,f4);
        System.out.println("Sum of three numbers = "+f5);

    }
}

输出:

Number I = 562.827
Number II = 900.981
Sum of two numbers = 1463.8081

Number III = -7367.76
Sum of three numbers = -5903.9517

例子2

import java.util.Scanner;

public class FloatSumExample2 {
    public static void main(String[] args) {
        Scanner scanner= new Scanner(System.in);
        Float a[] =new Float[6];

           System.out.println("Enter your Marks of following subjects");
            System.out.print("English:");
            a[0] = scanner.nextFloat();
            System.out.print("Maths:");
            a[1] = scanner.nextFloat();
            System.out.print("Science:");
            a[2] = scanner.nextFloat();
            System.out.print("S.St:");
            a[3] = scanner.nextFloat();
            System.out.print("Hindi:");
            a[4] = scanner.nextFloat();
            System.out.print("Computer:");
            a[5] = scanner.nextFloat();

            Float f7=0f;
           for (int i = 0; i < 5; i++) {
               f7 = Float.sum(a[i], a[i + 1]);
                a[i + 1] = f7;
            }
        Float f8= (f7)/6;
        System.out.println("Your percentage = "+f8+"%");
    }
}

输出:

Enter your Marks of following subjects
English:98
Maths:99
Science:78
S.St:76
Hindi:87
Computer:89
Your percentage = 87.833336%

例子3

public class FloatSumExample3 {
    public static void main(String[] args) {
        Float f1= Float.MIN_VALUE;
        Float f2= Float.MAX_VALUE;
        Float f3= Float.sum(f1,f2);
        System.out.println("1. Sum = "+f3);

        Float f4= Float.NEGATIVE_INFINITY;
        Float f5= Float.POSITIVE_INFINITY;
        // will return NaN value
        Float f6= Float.sum(f4,f5);
        System.out.println("2. Sum = "+f6);

        Float f7= (float) Float.MAX_EXPONENT;
        Float f8= (float) Float.MIN_EXPONENT;
        Float f9= Float.sum(f7,f8);
        System.out.println("3. Sum = "+f9);

    }
}

输出:

1. Sum = 3.4028235E38
2. Sum = NaN
3. Sum = 1.0






相关用法


注:本文由纯净天空筛选整理自 Java Float sum() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。