两重循环的多组测试数据练习: 1. 求k-n之间所有素数个数,输入多组k,n, 0,0结束 3 100 100 200 0 0 编程求解四则运算,有n组测试数据,double,小数点后2位 4 1
时间: 2024-12-13 16:22:49 浏览: 6
对于两重循环的多组测试数据练习,通常涉及编写程序解决特定问题,并能够处理不同类型和数量的数据输入。例如,你可以考虑以下Python代码来分别解决这两个问题:
**问题一:计算k到n之间的素数个数**
```python
def count_primes(k, n):
if k <= 0 or n <= 0:
return 0
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
primes = 0
for i in range(k, n + 1):
if is_prime(i):
primes += 1
return primes
# 测试数据
test_cases = [
(3, 100),
(100, 200),
# 结束标志
(0, 0),
]
for k, n in test_cases:
print(f"从{k}到{n}间的素数个数是: {count_primes(k, n)}")
```
**问题二:四则运算练习(n组double类型的测试数据,保留两位小数)**
```python
def perform_arithmetic_operations(n):
operations = []
for _ in range(n):
a, b, op = input().split()
a, b = float(a), float(b)
result = {
"+": a + b,
"-": a - b,
"*": a * b,
"/": a / b if b != 0 else "Error: Division by zero",
}[op]
result = round(result, 2)
operations.append((a, b, op, result))
return operations
# 测试数据
arithmetic_tests = 4
results = perform_arithmetic_operations(arithmetic_tests)
for i, operation in enumerate(results, start=1):
operator, a, b, result = operation
print(f"第{i}组:{a} {operator} {b} = {result}")
```
在这个例子中,我们分别为每个问题设计了一个函数,然后分别处理每组输入数据。如果你需要进一步的帮助或解释,随时告诉我哦!
阅读全文