[英]Switching If and Else Doesn't Produce Same Results
I've been working through some examples in The C Programming Language by K&R, but I'm kind of confused on a test that I did on exercise 1-12 where I switched the if and else statements. 我一直在研究K&R的C编程语言中的一些例子,但是我对练习1-12的测试感到困惑,我在那里切换了if和else语句。
The question goes as: Write a program that prints its input one word per line. 问题是:编写一个程序,每行打印一个输入的单词。
So basically to test out the \\n while ignoring multiple spaces in between words, I first wrote this. 所以基本上测试\\ n而忽略单词之间的多个空格,我首先写了这个。
#include <stdio.h>
int main()
{
int c;
while ((c = getchar()) != EOF) {
if (c == ' ' || c == '\t') {
printf("\n");
}
else {
putchar(c);
}
}
}
In this one, it would print out a new paragraph upon seeing blank spaces or tabs, and if it doesn't, then it copies exactly the input. 在这一个中,它会在看到空格或制表符时打印出一个新段落,如果没有,则会完全复制输入。
This code produced the results that I wanted (well there's still extra paragraphs from extra spaces in between words on input, but I'm ignoring that for now) 这段代码产生了我想要的结果(在输入的单词之间还有额外空格的额外段落,但我现在忽略了这一点)
Then I decided to see what happened if I switched my if and else statements while changing the conditions, but it turns out that the result is not the same. 然后我决定看看如果我在改变条件时切换了if和else语句会发生什么,但事实证明结果并不相同。
#include <stdio.h>
int main()
{
int c;
while ((c = getchar()) != EOF) {
if (c != ' ' || c != '\t') {
putchar(c);
}
else {
printf("\n");
}
}
}
In this one, I wanted it to print out whatever wasn't a blank space or tab, and if it doesn't, it would create a new paragraph. 在这一个中,我希望它打印出不是空格或制表符的内容,如果没有,则会创建一个新段落。
I expected that the new conditions would produce the same results. 我预计新条件会产生相同的结果。 Instead it just copied what I put inputted.
相反,它只是复制了我输入的内容。 Does anyone know why this doesn't work?
有谁知道为什么这不起作用?
if (c != ' ' || c != '\t') {
This condition checks to see whether either c
is not a space, or c
is not a tab. 此条件下进行检查以查看是否任何
c
不是空格, 或 c
不是标签。 This is always true, since c
can't be both a space and a tab at the same time. 这总是正确的,因为
c
不能同时是空格和制表符。 Try: 尝试:
if (c != ' ' && c != '\t') {
You can read about this principle in more detail at De Morgan's Laws . 您可以在De Morgan's Laws中更详细地了解这一原则。
An alternative approach would let the compiler do the logical negation for you: 另一种方法是让编译器为您做出逻辑否定:
if (!(c == ' ' || c == '\t')) {
however, some people (me included) would consider that harder to read because of the extra parentheses and the tiny !
然而,有些人(包括我在内)会因为额外的括号和微小的问题而认为更难阅读
!
on the left. 在左边。
the opposite of: 相反的:
if (c == ' ' || c == '\t') {
(the parameter c
is either a space or a tab) (参数
c
是空格或制表符)
is: 是:
if (c != ' ' && c != '\t') {
(the parameter c
is neither a space nor a tab) (参数
c
既不是空格也不是制表符)
the ||
||
should be changed to &&
. 应该改为
&&
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.