0

为什么当你放一个空的 if 语句时,程序仍然为一个整数变量产生一个值(零)?

这是一个简单的程序来比较三个整数并打印它们是否全部或任何一个大于 10。在第 42 行,有一个带分号的空 else 语句。如果用户输入 z 为 6,则程序不应返回 z1 =0。

#include <iostream> // include iostream class for input and output
#include <string> // for strings operation
#include <sstream> // for stringstream operations
using namespace std; // use defintion from std namespace

int main ()
{
   int x, y, z; // define three user-input integers
   int x1, y1, z1; // variables to hold bool values
   stringstream xyz; // variable to store whole bool value
   int XYZ; // variable to condiition print

   // prompt user for x, y and z input
   cout << "Please enter x" << "\n";
   cin >> x; 

   cout << "Please enter y" << "\n";
  cin >> y; 

  cout << "Please enter z" << "\n";
  cin >> z; 

  // generate bool values of x1, y1, z1
  if ( 10/x < 1)
     x1 = 1;
  else 
     x1 = 0;

  if ( 10/y  < 1)
     y1 = 1;
   else 
      y1 = 0;

  if ( 10/z  < 1)
     z1 = 1;
  else 
     ;


   // read into xyz and then XYZ
   xyz << x1 << y1 << z1;
   xyz >> XYZ;

  // generate 8 print statements
  if (XYZ == 111)
     ;

  if (XYZ == 000)
      cout << "x, y, z < 10" << endl;

  if (XYZ == 110)
     cout << "x, y > 10 and z < 10" << endl;

  if (XYZ == 101)
     cout << "x, z > 10 and y < 10" << endl;

  if (XYZ == 100)
  cout << "y, z < 10 and x > 10" << endl;

  if (XYZ == 011)
     cout << "y, z > 10 and x < 10" << endl;

  if (XYZ == 010)
     cout << "x, z < 10 and y > 10" << endl;

  if (XYZ == 001)
     cout << "x, y < 10 and z > 10" << endl;


} // program main ends 

我花了几个小时来研究这个,但大多数讨论都是关于 if 语句之后的分号语法错误或其他一些主题。

(注意:第 51 行已被更正以在控制台上不显示任何内容)。

有人在 Mac OSX 10.8.4 上遇到过这个问题吗?它与默认的 LLVM 编译器有关吗?

谢谢。

4

3 回答 3

3

正如评论中提到的那样 - 你变得(不)幸运了。

在 C++ 中,没有声明初始值的变量,如果从未赋值,则在被查询时最终可能具有任何值。有时这个值是 0,有时这个值是0xcccccccc,有时这个值是堆栈中的最后一个值——这取决于你的编译器、程序的内存布局、早餐吃什么等。

如果您不为 赋值z1,则无法对其行为做出假设。如果它最终为0,那只是巧合。

于 2013-07-13T02:32:55.010 回答
0

Jerry Coffin 在他对您的问题的评论中提到了这一点。我测试了它,这就是问题所在。您现在可能已经解决了它,但是您提供的文字实际上是八进制文字,而不是十进制,因此除非您很幸运,否则这些陈述不会是真的。

于 2013-07-19T11:29:01.750 回答
-4

在变量声明期间,z1 默认初始化为 0。因为如果 z=6,z1 不会被修改,所以 z1 将保持为 0。

于 2013-07-13T01:46:03.707 回答