负值未添加到Array

时间:2016-11-05 22:41:48

标签: c++ arrays class if-statement

问题

我有2个阵列,一个用于正数,一个用于负数。出于某种原因,如果要添加的第一个数字是负数,它会创建数组空间以添加数字,但插入的数字将始终为0.

添加代码

这是我的add方法,它确定值是负还是正,并将值添加到适当的数组:

{
  // init code for instance members
}

输出

通过以下测试:

bool MyClass::addInt(int valueToBeInserted){

 if (valueToBeInserted >= 0){
    if (posArrayIterator >= sizeOfMyArray){
      return false;
    } else {
      cout << "added " <<  valueToBeInserted << "\n" << endl;
      myPArray[posArrayIterator] = valueToBeInserted;
      posArrayIterator ++;
      return true;
    } 
  } else {
    if (negArrayIterator >= sizeOfMyArray){
      return false;
    } else {
      cout << "added " <<  valueToBeInserted << "\n" << endl;
      myNarray[negArrayIterator] = valueToBeInserted;
      negArrayIterator ++;
      return true;
    }
  }

}

预期输出为

b.addInt(-1);
b.addInt(-3);
b.addInt(-9);

但输出

[-1, -3, -9] 

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

由于你没有发布全班,我只能猜出问题所在。

1)posArrayIteratornegArrayIterator是否已初始化为0?他们应该是!

2)sizeOfMyArray的值是多少?

您的bool MyClass::addInt(int valueToBeInserted)

没有任何问题

见下面的例子:

class  MyClass
{
 private:
 int sizeOfMyArray;
 int posArrayIterator;
 int negArrayIterator;
 int myNarray[20];
 int myPArray[20];    

 public:
 MyClass(){
     sizeOfMyArray = 20;
     posArrayIterator = 0;
     negArrayIterator = 0;
  };

 bool addInt(int value); 
 void printNArray()
 {
   cout << "[ ";
   for (int i=0; i<negArrayIterator; i++)
   {
     cout << myNarray[i];
     if ( (i+1) < negArrayIterator ) 
     {
         cout << ", "; 
     }
   }
   cout << "]";
 }
};

 bool MyClass::addInt(int valueToBeInserted){

 if (valueToBeInserted >= 0){
    if (posArrayIterator >= sizeOfMyArray){
      return false;
    } else {
      cout << "added " <<  valueToBeInserted << "\n" << endl;
      myPArray[posArrayIterator] = valueToBeInserted;
      posArrayIterator ++;
      return true;
    } 
 } else {
        if (negArrayIterator >= sizeOfMyArray){
            return false;
        }
        else {
           cout << "added " <<  valueToBeInserted << "\n" << endl;
           myNarray[negArrayIterator] = valueToBeInserted;
           negArrayIterator ++;
           return true;
      }
 }
}

int main()
 {
  MyClass b;
  b.addInt(-1);
  b.addInt(-3);
  b.addInt(-9);
  b.printNArray();
  return 0;
 }

输出:

added -1

added -3

added -9

[ -1, -3, -9]