C ++数组练习 - 需要帮助

时间:2009-07-25 16:11:22

标签: c++ arrays

我是C ++ begginer。我从Deitel的书中做了这个练习:

  

使用一维数组来解决   以下问题。阅读20   数字,每个都在10之间   和100,包括在内。每个数字都是   阅读,验证并将其存储在   数组只有在不是重复的情况下才是   一个已经读过的数字。看完之后   所有值,只显示   用户输入的唯一值。   提供“最坏情况”   所有20个数字都不同。使用   解决这个问题的最小可能阵列   问题

这是我的代码:

#include <iostream>

using namespace std;

bool compare(int arrayNum[],int arraySize,int element);

int main()
{
    const int size=20;
    int i=1;
    int num[size];
    int arrayElement;
    int counter=0;

    while(i<=20)
    {

        cin>>arrayElement;
        if(i==1)    //stores first element in array
            num[0]=arrayElement;
        //compare new element with stored elements
        //if element is not a duplicate store it in array
        else if (compare(num,size,arrayElement))
        {
            counter++;
            num[counter]=arrayElement;
        }


        i++;
    }
    //displays array elements
    for(int k=0;k<=counter;k++)
        cout<<num[k]<<endl;

    return 0;
}

//compare elements in array

bool compare(int arrayNum[],int arraySize,int element)
{
    for(int j=0;j<arraySize;j++)
    {
        if(arrayNum[j]==element)
            return false;
    }

    return true;
}

它有效,但我不确定我是否正确解释了该任务。我假设我不必为数字范围(包括10到100)包含条件语句,因为这将从键盘读取并由我输入。那么为什么包括这个指令呢?最后还说

  

使用尽可能小的数组

我假设最大大小必须是20,但我不认为有一种方法可以动态扩展数组大小(例如在存储新元素时),因为数组大小是常量。如果有人能帮助我,我将不胜感激。欢迎任何有关代码或更好解决方案的评论。

5 个答案:

答案 0 :(得分:4)

  

读取每个数字时,验证   它并将其存储在数组

强调我的。该文明确指出您的程序必须验证输入。换句话说,它必须检查输入的数字是否在10到100之间,如果不是,则适当地处理错误。所以,是的,你确实需要一个条件,尽管你应该做的就是你应该做的事情。

你是对的,因为数组不能动态调整大小,所以数组大小必须至少为20。

答案 1 :(得分:2)

你确实需要有条件的。基本上它是指取10到100之间的数字。如果它不是这些范围之间的数字,则不要存储它。此外,如果数组中已存在该数字,请不要存储它。然后只打印出数组中的值。

您假设数组大小正确,它的最大大小为20,尽管您可能不会存储所有20个值(同样,因为某些输入可能不好)。

答案 2 :(得分:2)

最小的可能数组是char[12],其中各个位用作标志。

char data[12]; // memset(data, 0, sizeof(data)); in main();

void set(int n_raw;)
{
   int n = n_raw - 10;
   int index = n/8;
   int offset = n-8*index;
   data[index] |= 1 << offset; // added "1 <<"
}

回读这些值是留给学生的练习。

答案 3 :(得分:1)

  

我认为那时我不必包含   范围的条件陈述   这个数字(10到100,包括10和100)   将从键盘和   由我输入。因此,为什么呢   包括指示?

当然,在这种情况下,您编写了代码并知道输入预期范围内的数字;但是,始终验证用户的输入数据是一种标准的最佳做法,始终。这样就可以优雅地处理错误的值(带有适当的错误消息),并有助于使您的程序更加健壮。

  

最后还说

     
    

使用尽可能小的数组

  
     

我假设最大尺寸必须是20 ,,,

我认为他们可能在这里得到的是你可以使用一个91字节的数组,如下所示。

int cnt = 0;      // count of unique values entered
byte values[91];  // values entered indicator array
int valIdx;       // used as values array index

memset((void *)values, 0, sizeof(values));  // initialize array to all zeros

while ( cnt < 20 )
{
   // [code for the following comments not shown]
   //   have user input a number
   //   validate the number (>= 10 && <= 100) 
   //   subtract 10 from the number and store it in valIdx 
   //   (now valIdx will contain a number >= 0 <= 90)

   if ( !values[valIdx] )
   {
      values[valIdx] = 1;
      ++cnt;
   }
}

// then to show the unique values...

for ( valIdx = 0; valIdx < sizeof(values); valIdx++ )
{
   if ( values[valIdx] )
   {
      cout << valIdx + 10 << endl;
   }
}
然而,该解决方案不会满足“使用尽可能小的阵列”的要求。

返回您的代码......

我会继续添加用户输入验证,只是为了完整性(以及养成永不信任用户的习惯(特别是你自己)。

就改进而言,这是一件需要考虑的事情。当输入唯一编号时,比较例程将遍历每个数组元素。它只需要检查那些具有存储值的那些。进行这种更改也会导致你重构while循环的内容。

答案 4 :(得分:1)

我正在同一本书中学习C ++! 我解决这个问题的第一个实现是不使用任何互补数组的实现..它使用线性搜索来查找重复数据。

看看:

#include <iostream>
using namespace std;

// remember: size_t = unsigned int
const size_t arraySize = 20;
size_t _array[ arraySize ];

// global variable to keep track of the last used
// position in the _array
size_t counter = 0;

// the argument is not changed, so pass it by
// const reference
bool dupSearch( const int & );

int main()
{
    // disregard this
    ios_base::sync_with_stdio( false );

    // "temp" variable declared outside the loop to
    // avoid repeated allocation and deallocation
    int i = arraySize, temp;

    // look at the loop condition below " ( i-- ) "
    // remember:
    // false = ( every expression evaluated to 0 )
    // true  = ( every expression evaluated to a non-zero result )
    // more details on pag. 108 of the book. 8/e Portability tip 4.1
    while ( i-- )
    {
        // read the number from the user
        cin >> temp;

        // if the number entered is valid, put the
        // number on _array[ counter ] and increment 'counter'
        if ( dupSearch( temp ))
        {
            _array[ counter ] = temp;
            ++counter;
        }
    }

    // print the result in column format
    cout << endl;
    for ( size_t j = 0; j < counter; ++j )
        cout << _array[ j ] << endl;
}

// validation: if the value is out of the described range, return false
// if is in the range, check for duplicates using linear search.
// if a duplicate is found, return false
// otherwise, return true.
bool dupSearch( const int &a )
{
    if ( a < 10 || a > 100 )
        return false;
    else
        for ( size_t i = 0; i < counter; ++i )
            if ( _array[ i ] == a )
                return false;

    return true;
}

比较次数为
n = ( n * ( n + 1 )) / 2
其中 n = 计数器。最坏的情况 - &gt; counter = 20个数字 - &gt;通过程序执行循环210次。

相关问题