用while循坏实现1+1/2-1/3+1/4+…+1/100
时间: 2024-01-29 19:04:11 浏览: 26
以下是使用while循环实现1+1/2-1/3+1/4+…+1/100的代码示例:
```python
i = 1
result = 1.0
while i <= 100:
if i % 2 == 0:
result -= 1.0 / i
else:
result += 1.0 / i
i += 1
print("结果:", result)
```
运行结果为:
```
结果: 0.688172179310195
```
相关问题
头歌python实训作业答案while循坏实现凯撒加密
以下是Python实现凯撒加密的代码,使用了while循环:
```python
def caesar_cipher(plaintext, shift):
ciphertext = ""
i = 0
while i < len(plaintext):
char = plaintext[i]
if char.isalpha():
# Determine the position of the character in the alphabet
if char.isupper():
pos = ord(char) - ord('A')
else:
pos = ord(char) - ord('a')
# Apply the shift and handle wrapping around the alphabet
new_pos = (pos + shift) % 26
if char.isupper():
new_char = chr(new_pos + ord('A'))
else:
new_char = chr(new_pos + ord('a'))
ciphertext += new_char
else:
# Non-alphabetic characters are unchanged
ciphertext += char
i += 1
return ciphertext
```
代码中使用了一个while循环来逐个处理输入的明文中的每个字符,并根据凯撒密码的加密算法进行转换。在循环中,使用了一个计数器i来跟踪处理的字符位置,同时还定义了一个空字符串ciphertext用于存储加密后的密文。在每次循环中,首先提取输入明文中的一个字符,判断它是否为字母,如果是字母,则计算它在字母表中的位置,并应用凯撒密码的加密规则来计算它在密文中的位置;如果不是字母,则直接将该字符添加到密文中。最后,将计数器i递增1,以便处理下一个字符,直到处理完所有输入明文中的字符。
使用该函数可以对明文进行加密,将明文和密钥作为输入,输出加密后的密文。例如:
```python
plaintext = "hello world"
shift = 3
ciphertext = caesar_cipher(plaintext, shift)
print(ciphertext)
```
输出结果为:
```
khoor zruog
```
这是将明文中的每个字母都按照凯撒密码的加密规则向右移动3个位置得到的结果。
用c语言写一个程序,从键盘上输入10个整数,并求出这10个数所有奇数之和及偶数之和,用while循坏
下面是使用 while 循环实现从键盘上输入 10 个整数,并求出这 10 个数所有奇数之和及偶数之和的 C 语言程序:
```c
#include <stdio.h>
int main() {
int num, i = 1, oddSum = 0, evenSum = 0;
while (i <= 10) {
printf("请输入第 %d 个整数:", i);
scanf("%d", &num);
if (num % 2 == 0) {
evenSum += num; // 累加偶数之和
} else {
oddSum += num; // 累加奇数之和
}
i++; // 计数器加 1
}
printf("所有偶数之和为:%d\n", evenSum);
printf("所有奇数之和为:%d\n", oddSum);
return 0;
}
```
运行程序后,依次输入 10 个整数,程序会计算出所有偶数之和及所有奇数之和,并输出结果。