gpt4 book ai didi

C K&R 1.5.4 字数统计练习 1-9

转载 作者:太空宇宙 更新时间:2023-11-04 01:08:34 25 4
gpt4 key购买 nike

我想知道为什么下面的代码不能完全像下面的代码那样工作。代码应该做的是删除多个连续的空格并只显示一个空格:所以“它有效”变成“它有效”。第一段代码只是让它看起来“有效”。

没用

#include <stdio.h>

main(){
int c;
int lastspace;

lastspace = 0;
while((c = getchar()) != EOF){
if(c != ' ')
putchar(c);
lastspace = 0;
if(c == ' '){
if(lastspace == 0){
lastspace = 1;
putchar(c);
}
}
}
}

作品

#include <stdio.h>

main(){
int c
int lastspace;

lastspace = 0;
while((c = getchar()) != EOF){
if(c != ' ')
putchar(c);
if(c == ' '){
if(lastspace != c){
lastspace = c;
putchar(c);
}
}
}
}

最佳答案

在你的第一个例子中

if(c != ' ')
putchar(c);
lastspace = 0;

不会在 if 语句之后放置 {} 大括号,因此只有紧随其后的语句有条件地执行。更改缩进并添加大括号表明代码实际上是

if(c != ' ') {
putchar(c);
}
lastspace = 0;

这就是为什么某些编码标准要求在所有控制语句之后使用 {} 的原因。

关于C K&R 1.5.4 字数统计练习 1-9,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17998921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com