Provide Best Programming Tutorials

编程作业 — 运算符

(将摄氏溫度转换为华氏溫度)

编写程序,从控制台读人 double 型的摄氏温度,然后将其转换为华氏温度 ,并且显示结果。转换公式如下所示:
华氏温度 (9/5) x 摄氏温度+32

提示:在 Java中,9/5的结果是1,但是9.0/5的结果是1.8。

下面是一个运行例子:

Enter a degree in Celsius : 43

43 Celsius is 109.4 Fahrenheit

import java.util.Scanner;
 
public class E4_01 {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a degree in Celsius: ");
    double celsius = input.nextDouble();
 
    double fahrenheit = celsiusToFahrenheit(celsius);
 
    System.out.println(celsius + " Celsius is " + fahrenheit + " Fahrenheit");
  }
 
  private static double celsiusToFahrenheit(double celsius) {
    return (9.0 / 5) * celsius + 32;
  }
}

(计算圓柱体的体积)

编写程序,读人圆柱体的半径和高,并使用下列公式计算圆柱的体积:

面积=半径 x 半径 x p

体积=面积 X 高

下面是一个运行示例:

Enter the radius and length of a cylinder : 5.512

The area is 95.0331
The volume is 1140.4

import java.util.Scanner;
 
public class E4_02 {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter the radius and length of a cylinder: ");
    double radius = input.nextDouble();
    double length = input.nextDouble();
 
    double area = areaOfCylinder(radius);
    double volume = volumeOfCylinder(area, length);
 
    System.out.println("The area is " + area);
    System.out.println("The volume is " + volume);
  }
 
  private static double areaOfCylinder(double radius) {
    return radius * radius * Math.PI;
  }
 
  private static double volumeOfCylinder(double area, double length) {
    return area * length;
  }
}

(将英尺转換为米)

编写程序,读人英尺数,将其转换为米数并显示结果。一英尺等于0.30S 米。

下面是运行示例:

Enter a value for feet:16.5

16.5 feet is S.0325 meters

import java.util.Scanner;
 
public class E4_03 {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a value for feet: ");
    double feet = input.nextDouble();
 
    double meters = feetToMeters(feet);
 
    System.out.println(feet + " feet is " + meters + " meters");
  }
 
  private static double feetToMeters(double feet) {
    return feet * 0.305;
  }
}

(使用操作符&& 、丨丨和 ^ 编写一个程序,提示用户输入一个整数值,然后判定它是否能被5 和 6 整除,是否能被5 或6 整除,以及是否能被5 或6 整除但是不能同时被它们整除3 下面是这个程序的运行示例:

Enter an integer: 10

Is 10 divisible by 5 and 6? false

Is 10 divisible by 5 or 6? true

Is 10 divisible by 5 or 6, but not both? true

import java.util.Scanner;
 
public class E4_04 {
 
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter an integer: ");
    int n = input.nextInt();
 
    System.out.println("Is " + n + " divisible by 5 and 6? " +
        (n % 5 == 0 && n % 6 == 0));
    System.out.println("Is " + n + " divisible by 5 or 6? " +
        (n % 5 == 0 || n % 6 == 0));
    System.out.println("Is " + n + " divisible by 5 or 6, but not both? " +
        (n % 5 == 0 ^ n % 6 == 0));
  }
}

Leave a Reply

Close Menu