我用Java創建了一個程式,它使用戶鍵入兩點坐標,然后該程式計算斜率。有誰知道如何解決程式顯示實際斜率而不是 0.0 的問題?
import java.util.Scanner;
public class Slope
{
public static void main(String[] args)
{
double y1,y2,x2,x1;
float slope = 0;
Scanner SC = new Scanner(System.in);
System.out.println("Enter coordinates for point X1");
x1 = SC.nextDouble();
System.out.println("Enter coordinates for point Y1");
y1 = SC.nextDouble();
System.out.println("Enter coordinates for point X2");
x2 = SC.nextDouble();
System.out.println("Enter coordinates for point Y2");
y2 = SC.nextDouble();
System.out.print("\nThe points are: (" x1 "," y1 ") and (" x2 "," y2 ")");
double Slope = (y2-y1)/(x2-x1);
System.out.println("\nthe slope is:" slope);
}
}
uj5u.com熱心網友回復:
我已經為你重新編碼了,其中:
- 解決問題
- 使代碼更小且非冗余
- 引入模塊化
import java.util.Scanner;
public class Slope
{
static Scanner SC = new Scanner(System.in);
public static double double_input(String message)
{
System.out.print(message);
return SC.nextDouble();
}
public static void main(String[] args)
{
double y1, y2, x2, x1, slope = 0;
x1 = double_input("Enter coordinates for point X1 : ");
y1 = double_input("Enter coordinates for point Y1 : ");
x2 = double_input("Enter coordinates for point X2 : ");
y2 = double_input("Enter coordinates for point Y2 : ");
System.out.print("\nThe points are: (" x1 "," y1 ") and (" x2 "," y2 ")");
slope = (y2-y1)/(x2-x1);
System.out.println("\nthe slope is: " slope);
}
}
出現問題是因為您已將計算值宣告并存盤到另一個變數“斜率”中,但您正在列印另一個“斜率”。
uj5u.com熱心網友回復:
您正在創建兩個變數“斜率”和“斜率”。她們不一樣。您正在列印一個名為 'slope' 的值,它在初始化時為 0。
您應該列印一個名為“Slope”的(后一個)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/334819.html
標籤:爪哇
下一篇:如何對int亂數和雙亂數求和?
