Arizona State University (ASU) CSE110 Principles of Programming Exam 1 Practice

Session length

1 / 500

Which of the following correctly simulates the toss of two coins?

(int) (Math.random() * 0 + 1)

(int) (Math.random() * 1 + 1)

(int) (Math.random() * 2)

(int) (Math.random() * 2) + (int) (Math.random() * 2)

To understand why the choice that simulates the toss of two coins correctly is the one that involves adding the results of two separate random coin tosses, it’s important to first grasp how simulating a coin toss works.

Each coin can either land on heads or tails, which we can represent as 0 and 1, respectively. Therefore, a single toss can be simulated by generating a random number either 0 or 1. In programming, this can be achieved using `Math.random()`, which generates a floating-point number between 0.0 (inclusive) and 1.0 (exclusive). By scaling this value, we can produce integers that represent the outcome of a coin toss.

When tossing two coins, we want two outcomes. The correct simulation, which involves adding two separate results from `Math.random()`, allows us to consider both coin tosses independently. Here’s how it works:

1. The expression `(int) (Math.random() * 2)` generates a 0 (tails) or a 1 (heads), simulating one coin toss.

2. When you run this expression twice (once for each coin), you can add the results together. This results in an integer that can range from 0 (

Get further explanation with Examzify DeepDiveBeta
Next Question
Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy