老师说,只要c
是负的,那么:"变量a
是负的",但这是没有意义的。
程序是否以错误的形式编写?
在我看来,else应该是if(a>0)
和{}
的一部分。我不知道他为什么选择不用它。
总之,正确的形式是:if(a>0){...}else
和cout
吗?
#include <iostream>`
using namespace std;
int main(void) {
int a, b, c;
cin >> a;
cin >> b;
cin >> c;
if (a > 0)
if (b > 0)
if (c > 0)
cout << "they are all positive";
else
cout << "the number a is negative";
}
你的老师是对的。else
适用于最新的if
,因此c
的值决定输出。(更具体地说,只有当a
和b
都为正时,程序才会打印一些东西。)您可以通过运行程序来测试。
输出&;数字a是负的&;是不合逻辑的,因为这才是测试的目的。程序是故意写错的。如果所有问题的答案都很明显,每个人都会得到最好的成绩。
您需要使用curly brackets
,否则else
将仅适用于newest if
。当a
和b
都是positive
时,程序只会显示print
。
这里的核心问题是缺乏关于程序应该做什么的明确规范。我怀疑你确实有它,但是没有它在这里,我只能解释代码是做什么的,以及如何从老师的引用可以被理解为描述代码的功能。
这里可视化的是一个修改版本的代码,这是不言自明的(我希望):
#include <iostream>
using namespace std;
int main(void) {
int a, b, c;
cin >> a;
cin >> b;
cin >> c;
if (a > 0)
if (b > 0)
if (c > 0)
cout << "they are all positive"; // true
else
cout << "the number 'c' is negative or zero, 'a' and 'b' are positive";
else
cout << "the number 'b' is negative or zero , 'a' is positive, no idea about 'c'";
else
cout << "the number 'a' is negative or zero , no idea about 'b' and 'c'";
}
我怀疑这个输出"不知道"是你可能想要使用更多的if
s,为了描述其他数字。
注:我坚持你的风格(没有{}
)。但我建议不要吝啬。根据我的经验,它使生活更容易,在我看来,它使代码更易读。
我认为老师的话
当c值为负值时,它显示:"a数是负的;但这没有意义
应读作:
'当c值为负(其他两个为正)时,此代码输出:'a'数为负',但这没有意义,因为当此输出发生时,a
实际上是正的。
我同意。