下列程序用来对从键盘上输入的两个字符串进行比较,然后输出两个字符串中第一个不相同字符的ASCII码之差。例如:输入的两个字符串分别为abcdef和abceef,则输出为-1。请填空。 #include <stdio.h> #include <string.h> void main() { char str1[100],str2[100],c; int i,s; printf("\n input string 1:\n"); gets(str1); printf("\n input string 2:\n"); gets(str2); i=0; while((str1[i]==str2[i])&&(str1[i]!= 输入答案 )) i++; s= 输入答案 ; printf("%d\n",s); }
时间: 2024-01-22 08:03:01 浏览: 31
答案:
```
#include <stdio.h>
#include <string.h>
void main() {
char str1[100],str2[100],c;
int i,s;
printf("\n input string 1:\n");
gets(str1);
printf("\n input string 2:\n");
gets(str2);
i=0;
while((str1[i]==str2[i])&&(str1[i]!='\0'))
i++;
s= str1[i]-str2[i];
printf("%d\n",s);
}
```
解析:
1. 在比较字符串时,应该判断两个字符串中是否有一个到达了字符串的结尾(即 `\0`),所以第一个空格应该填 `\0`。
2. 计算两个字符串第一个不相同字符的 ASCII 码之差,只需要将两个字符相减即可。
3. 注意输入字符串时,应该使用 `fgets` 替代 `gets` 函数,以避免缓冲区溢出的问题。
相关问题
程序设计用来对从键盘上输入的两个字符串进行比较,然输出两个字符串中第一个不 相同字符的ASCI码之差
以下是Python 3的代码实现:
```python
str1 = input("请输入第一个字符串:")
str2 = input("请输入第二个字符串:")
for i in range(min(len(str1), len(str2))):
if str1[i] != str2[i]:
print("两个字符串第一个不相同的字符的ASCI码之差为:", ord(str1[i]) - ord(str2[i]))
break
else:
print("两个字符串完全相同")
```
代码说明:
1. 首先从键盘上输入两个字符串。
2. 使用`range`函数循环遍历两个字符串中较短的那个字符串。
3. 在循环中,如果两个字符串的当前字符不相同,则输出它们的ASCI码之差,并退出循环。
4. 如果循环正常结束,说明两个字符串完全相同,输出相应的提示信息。
编写程序实现,对键盘输入的两个字符串进行比较,然后输出两个字符串中第一个不相同字符的ASCII码之差
好的,这是一个简单的 Python 实现:
```python
str1 = input("请输入第一个字符串:")
str2 = input("请输入第二个字符串:")
for i in range(min(len(str1), len(str2))):
if str1[i] != str2[i]:
print("两个字符串中第一个不相同字符的ASCII码之差为:", ord(str1[i]) - ord(str2[i]))
break
else:
print("两个字符串完全相同")
```
输入两个字符串后,程序会逐个字符比较它们,直到找到第一个不相同的字符为止。然后输出这两个字符的 ASCII 码之差。如果两个字符串完全相同,则输出一个提示。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)