如何修改Python随机数生成程序使其运行指定次数并统计目标数生成次数
Modified RNG Program: Fixed Run Count + Target Occurrence Tracking
Alright, let's adjust your random number generator to run a specific number of times and count how often your target number appears. Here's a polished, functional version of your code with key improvements:
from random import randint # Get and validate target number input print("What would you like to test-roll today?") print("(64, 128, 256, 384, 512, 1024, 5000)") target_input = input().strip() loot_table = {"64":64, "128":128, "256":256, "384":384, "512":512, "1024":1024, "5000":5000} if target_input not in loot_table: print("Oops! That's not a valid option. Please choose from the listed numbers.") exit() target_number = loot_table[target_input] # Get and validate number of runs (ensures positive integer input) print(f"\nHow many total rolls would you like to perform?") while True: try: total_runs = int(input().strip()) if total_runs > 0: break print("Please enter a positive number—can't roll zero or negative times!") except ValueError: print("That's not a number. Try again with an integer.") # Track occurrences of the target number target_hits = 0 # Execute the specified number of rolls for _ in range(total_runs): current_roll = randint(1, target_number) if current_roll == target_number: target_hits += 1 # Output clear, formatted results print(f"\n--- Roll Results ---") print(f"Total rolls performed: {total_runs}") print(f"Times {target_number} was rolled: {target_hits}") print(f"Frequency: {target_hits/total_runs:.2%}")
Key Changes Explained
- Input Validation: Added checks to make sure users enter valid target numbers and positive integers for run counts—prevents crashes from bad input.
- Fixed Loop Execution: Replaced the "stop on target hit" logic with a
forloop that runs exactlytotal_runstimes, as requested. - Hit Tracking: A
target_hitscounter increments every time the target number is rolled, so we can report the total at the end. - Enhanced Output: Includes a percentage frequency to make the stats easier to interpret.
内容的提问来源于stack exchange,提问作者rantof63
相关产品推荐
相关产品推荐

