#22624: JAVA一直NA 求解


chosixi (unknown)


寫的程式如下,不知道哪裡錯誤

再麻煩大大求解

 

 

import java.util.Scanner;

 

/*

 * To change this license header, choose License Headers in Project Properties.

 * To change this template file, choose Tools | Templates

 * and open the template in the editor.

 */

/**

 *

 * @author cho02

 */

public class Main {

 

    /**

     * @param args the command line arguments

     */

    public static void main(String[] args) {

        // TODO code application logic here

 

        Scanner sc = new Scanner(System.in);

        while (sc.hasNextInt()) {

            int a = sc.nextInt();

            int b = sc.nextInt();

            int c = sc.nextInt();

 

            int d = (b * b) - (4 * a * c);

 

            if (d < 0) {

                System.out.println("No real root");

            } else if (d == 0) {

                int ans;

                ans = -b  / 2 * a;

                System.out.printf("Two same roots x=%d", ans);

            } else if (d > 0) {

                int ans, ans1;

                ans = (-b + (int) (Math.sqrt(d))) / 2 * a;

                ans1 = (-b - (int) (Math.sqrt(d))) / 2 * a;

                System.out.printf("Two different roots x1=%d , x2=%d", ans, ans1);

            }

 

        }

 

    }

 

}

 

#22634: Re:JAVA一直NA 求解


snakeneedy (蛇~Snake)


我猜是 printf 的字串結尾少了個換行 \n

#22635: Re:JAVA一直NA 求解


snakeneedy (蛇~Snake)


看到另外一個問題是算式錯誤

ans = (-b + (int) (Math.sqrt(d))) / 2 * a;
  ans1 = (-b - (int) (Math.sqrt(d))) / 2 * a;

應該為

ans = (-b + (int) (Math.sqrt(d))) / (2 * a);
ans1 = (-b - (int) (Math.sqrt(d))) / (2 * a);