コーディングテスト練習記録

4721 ワード

2021.12.21初日
白準2562号(最低価格)
質問する
9つの異なる自然数を与える場合は、プログラムを作成し、その中の最値を見つけ、最値がいくつかの数であることを求めます.
例えば、9つの異なる自然数
3, 29, 38, 12, 57, 74, 40, 85, 61
もしあげたら、彼らの中の最高価格は85で、この価格は8番目です.
私の答え
  • for文nextIntを使用してint配列で9個の自然数
  • を得る
  • の最大値、maxIndexはタイル1位で、タイル[0]の大きな値を比較すると
  • に置き換えられます.
    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
    
            int[] nArr = new int[9];
            int max = nArr[0];
            int maxIndex = 0;
    
            for (int i = 0; i < 9; i++) {
                nArr[i] = scanner.nextInt();
                if (max < nArr[i]) {
                    max = nArr[i];
                    maxIndex = i + 1;
                }
            }
            System.out.println(max);
            System.out.println(maxIndex);
        }
    }
    考える
  • アレイを使用することなく、
  • にアクセスできます.