3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

paiza×Qiita記事投稿キャンペーン「プログラミング問題をやってみて書いたコードを投稿しよう!」

Paiza×Qiitaキャンペーン Javaで解説してみた【D N倍の文字列 編】

Last updated at Posted at 2024-08-20

問題へのリンク

解答コード

詳細

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);

		final int M = scanner.nextInt();
		final int P = scanner.nextInt();
		final int Q = scanner.nextInt();

		double answer = M * (100 - P) * (100 - Q);
		answer /= 100.0 * 100.0;

		System.out.println(answer);
		scanner.close();
	}
}


10進数計算

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);

		final BigDecimal M = BigDecimal.valueOf(scanner.nextLong());
		final BigDecimal P = BigDecimal.valueOf(scanner.nextLong());
		final BigDecimal Q = BigDecimal.valueOf(scanner.nextLong());

		BigDecimal unsolded = sold(M, P);
		BigDecimal answer = sold(unsolded, Q);

		System.out.println(answer);
		scanner.close();
	}

	private static final BigDecimal HUNDRED = BigDecimal.valueOf(100);

	private static BigDecimal sold(BigDecimal food, BigDecimal salePercentage) {
		BigDecimal remainingPercentage = HUNDRED.subtract(salePercentage);
		BigDecimal unsolded = food.multiply(remainingPercentage).divide(HUNDRED,4,RoundingMode.HALF_UP);
		return unsolded;
	}
}

}


# 解説
詳細

人間はこじらせている人以外は10進数で計算を行いますが、コンピュータは2進数で計算を行います。循環小数になる条件が10進数と2進数で異なる為、基本的に整数計算で行い、最後に除算を行うと誤差が最小限に抑えられます。
具体的には、分母・分子が整数かつ約分済み分数表記を行った際に、分母が2の乗数で表記できるならば誤差は出ません。10進数の場合は、分母が2の乗数と5の乗数の

10進数計算
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?