簡體   English   中英

Java 未提供表達式的預期結果

[英]Java not providing expected result for a expression

我正在嘗試實現以下表達式 s=ut+½at² 但它沒有給出u = 2, a = 2, t = 1 => s = 3.00 m的預期結果

我試過移動括號/括號,但它不能解決問題......

import java.util.Scanner;
public class Exercise4 {
    public static void main(String args[]) {
        float speed, time, acceleration, distance;
        Scanner input = new Scanner(System.in);
        System.out.print("Please enter the initial speed: ");
        speed = input.nextFloat();
        System.out.print("Please enter the acceleration: ");
        time = input.nextFloat();
        System.out.print("Please enter the time spent traveling: ");
        acceleration = input.nextFloat();
        distance = (speed * time) + (((0.5 f * acceleration) * time) * time);
        System.out.println("The object traveled a distance of " + String.format("%.2f", distance) + " metres");
    }
}

其他有效的預期結果是:

u = 0, a = 0, t = 0 => s0 .00 m
u = 0, a = 1, t = 1 => s0 .50 m
u = 1, a = 1, t = 1 => s1 .50 m

您弄亂了輸入的順序。 您要求加速度的值,但將該輸入分配給time變量。

System.out.print("Please enter the acceleration: ");
        time = input.nextFloat();

只需更改順序,它就可以正常工作。

import java.util.Scanner;

public class Exercise4 {
    public static void main(String args[]) {
        float speed, time, acceleration, distance;
        Scanner input = new Scanner(System.in);
        System.out.print("Please enter the initial speed: ");
        speed = input.nextFloat();
        System.out.print("Please enter the acceleration: ");
        acceleration = input.nextFloat();
        System.out.print("Please enter the time spent traveling: ");
        time = input.nextFloat();
        distance = (speed * time) + (((0.5f * acceleration) * time) * time);
        System.out.println("The object traveled a distance of " + String.format("%.2f", distance) + " metres"); 
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM