【问题标题】:C++ array excercise-help needed需要 C++ 数组练习帮助
【发布时间】:2009-07-25 16:11:21
【问题描述】:

我是 C++ 初学者。我从 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,但我认为没有办法动态扩展数组大小(例如在存储新元素时),因为数组大小是 const。如果有人可以帮助我,我将不胜感激。欢迎任何有关代码或更好解决方案的 cmets。

【问题讨论】:

  • 如果程序应该验证数字以确保它不是重复的,那么在显示数组时它不是唯一的吗?哦,+1 自学者
  • 我将于 10 月开始攻读硕士软件工程硕士课程,其中 C++ 被用作主要编程语言。我正在努力自己学习,以在全日制学习的同时保住我的全职工作(仅限夜校)。感谢 +1 ;)

标签: c++ arrays


【解决方案1】:

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

强调我的。文本清楚地表明您的程序必须验证输入。换句话说,它必须检查输入的数字是否在 10 到 100 之间,如果不是,则适当地处理错误。所以是的,你确实需要一个条件,尽管你如何处理错误取决于你。

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

【讨论】:

  • "如何处理错误取决于您"。无论如何,这个问题有点不清楚这意味着什么。我想说,因为它说“读取范围内的 20 个值”,所以超出范围的值不应算作 20 个值之一,请继续阅读,直到您看到 20 个范围内的值。但它们可能意味着数字将都在范围内,并且“验证”意味着“检查重复项”。或者它们可能意味着程序在看到无效数据时应该停止,作为一种防御性编程措施。糟糕的不完整规范;-)
  • 没错,规范尚不清楚,您可以为它做一个简单的说明,即“验证该数字不是重复的”。我认为可以公平地假设它也应该被验证在 10-100 范围内。是的,我们在 uni 学到的规则很简单,“当规范不完整时,只要做出你喜欢的任何假设,但记录下来”。 :)
  • 我希望我的客户能采纳这条规则。
  • 呵呵是的,但是在教学环境中进行练习等是有意义的。
【解决方案2】:

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

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

【讨论】:

  • 当它说“可能的最小数组”时,我将其解释为数组的最小大小,而不是存储在数组中的最小数量的值。我想我让它比原来更复杂:)。无论如何感谢您的帮助。
【解决方案3】:

可能的最小数组是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 <<"
}

回读这些值留给学生作为练习。

【讨论】:

  • 是否需要进行位移?偏移量是一个从 0 到 7 的数字,在提取 8 倍后(也可以用模数来完成:n%8)。数据[索引] |= (1
  • 技术上是正确的,但您不再将数组用作数组。如果预期的解决方案是实现 bitset,我认为作业文本会提到它。 :)
  • 谢谢史蒂夫和安德鲁,但老实说我不明白。也许我需要了解更多,因为我不知道 "
  • @Pat:他使用 12 * 8 = 96 位作为标志——如果他读取数字 10,那么他会在第一个字符中设置第一位。如果他读取数字 100,则设置最后一个字符的第二位(总共第 90 位)。然后通过检查所有位并写入设置的位来打印出值。
  • 可爱,但可能比预期的答案更优化。
【解决方案4】:

我假设我不必包括 范围的条件语句 数字(包括 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 循环的内容。

【讨论】:

    【解决方案5】:

    我正在同一本书中学习 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 = 计数器。最坏的情况 --> 计数器 = 20 个数字 --> 在程序执行过程中循环 210 次。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多