1. 程式人生 > >簡單四則運算一

簡單四則運算一

運算 AI 跳過 else pos java http OS HA

import java.util.Random;
import java.util.Scanner;

public class Num {

public static void main(String[] args) {
    System.out.println("練習題數:");
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    System.out.println("---------------------");
    
    int c =0;
    int result = 0;//計算結果
    int count = 0;//正確題數

    for (int j = 0; j <n; j++) {
        Random random = new Random();//運算數
        int a = random.nextInt(100);
        int b = random.nextInt(100);
        
        char[] ch = {‘+‘,‘-‘,‘*‘,‘/‘};
        Random ran = new Random();//運算符
        int i = ran.nextInt(ch.length);
        
        switch(i){
        case 0:
            System.out.println(a+"+"+b+"= ?");
            result=a+b;
            c++;
            break;
        case 1:
            System.out.println(a+"-"+b+"= ?");
            result=a-b;
            c++;
            break;
        case 2:
            System.out.println(a+"*"+b+"= ?");
            result=a*b;
            c++;
            break;
        case 3:
            System.out.println(a+"/"+b+"= ?");
            //除法運算結果取整
            float x = a;
            float y = b;
            if(y!=0){
                result =(int)(x/y);    
                }
            else{
                System.out.println("分母有誤,跳過上題 ");
                break;
            }
            c++;
            break;
        }

    System.out.println("請輸入答案: ");
    float an = sc.nextFloat();//輸入計算結果
    
    if(an==result){
          System.out.println("你真棒o( ̄▽ ̄)d -------");
          count++;
        }else{
            System.out.println("回答錯誤"+"--正確結果為: "+result+"---繼續努力ヾ(?°?°?)??------");
        }
    }

    System.out.println("輸出的題數共:"+c+"------共答對"+count+"道題");
}

}
技術分享圖片

技術分享圖片

簡單四則運算一