【问题标题】:Dynamic array that halfs the biggest element and creates a new one c++将最大元素减半并创建一个新元素的动态数组 c++
【发布时间】:2020-04-15 03:02:26
【问题描述】:

所以任务是这样的: 用户必须输入数组中元素的数量,它们必须>3 和 键入 1,程序必须找到数组中的最大数字,一半,程序应该找到新数组像那样 [2 4 6 4 4 2] 但是,如果用户输入了 3 或其他数字,程序应该找到最大的 num,一半,然后再次找到最大的 num,一半,类似这样(它确实是用户拥有 typer / 用户拥有的 num键入 3-> 它找到最大的 num,halfs,找到新的最大的,将其减半,找到新的最大的,将其减半)。此外,如果数组中的数字只有 2 2 2 2,程序应该 cout “再试一次”

到目前为止,我已经完成了这项工作,请帮助我,我是这些事情的新手,我需要帮助。

#include <iostream>

using namespace std;

int main ()

{

  int i,n, numa, half;

  int * p;

  cout << "How many numbers would you like to type? ";

  cin >> i;

  p= new (nothrow) int[i];

  if(i<4 || i>1024)
{

      cout<<"Invalid input!";

      return 1;

  }

  if (p == nullptr)

    cout << "Error: memory could not be allocated";

  else

  {

    for (n=0; n<i; n++)

    {

      cout << "Enter number: ";

      cin >> p[n];

    }

    cout<<"A<num>, enter a number: "; //thats how many times u have to find the biggest num and half it

    cin>>numa;

    for(i = 1; i < n; ++i)

    {

       if(p[0] < p[i])

           p[0]=p[i];
    }

    cout<<p[0]<<endl;

    half=p[0]/2;

    cout<<half<<endl;
  }


  delete[] p;

  return 0;

}

【问题讨论】:

  • 您好,为了让其他人更好地阅读您的代码,请使用Markdown formatting
  • 无关:p= new (nothrow) int[i]; 是您只有在有充分理由时才应该做的事情。如果数组分配失败,比如没有内存,你希望程序抛出异常。这就是特殊事件例外的类型。
  • 任务是使用动态数组:)
  • 注意:一次,您颠倒了in 的角色。这使程序更难阅读。更好的是使用有意义的名称作为size
  • 如果将一个数字减半两次或多次以使其变为奇数,该怎么办?例如。 6/2 = 3,然后 3/2 = 1.5,..

标签: c++ arrays input dynamic output


【解决方案1】:

在 C++ 中,动态“数组”将由 std::vector 处理。您可以在此处阅读以了解更多详细信息。

您的问题/任务/要求不是很清楚,而且有点难以理解。无论如何,据我了解,我已将整体任务拆分为较小的任务,并为您创建了一些演示。

如果不是你所期望的,那么请给我一个更好的描述,我会修改它。

请查看众多可能的解决方案之一:

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

constexpr size_t MinNumberElementsInVector = 4U;
constexpr size_t MaxNumberElementsInVector = 1024U;

size_t getNumberOfVectorElements() {
    // inform user, what to do
    size_t result{ 0U };

    do {
        std::cout << "\nPlease enter, how many numbers the test array should have.\n"
            "The given number must be >=" << MinNumberElementsInVector << "and <="
            << MaxNumberElementsInVector << ".\nPlease enter: ";

        // Get value from user and check range
        if (!((std::cin >> result) && (result >= MinNumberElementsInVector) && (result <= MaxNumberElementsInVector))) {
            // Error in input. Reset result to 0 and show error message
            result = 0U;
            std::cout << "\n\nError during input. Try Again.\n\n";
        }
    } while (0 == result);
    return result;
}
size_t getNumberOfActions() {
    // inform user, what to do
    size_t result{ 0U };

    do {
        std::cout << "\n\nPlease enter, how many times the half operation should be done.\n"
            "The given number must be > 0.\nPlease enter: ";

        // Get value from user and check range
        if (!((std::cin >> result) && (result > 0))) {
            // Error in input. Reset result to 0 and show error message
            result = 0U;
            std::cout << "\n\nError during input. Try Again.\n\n";
        }
    } while (0 == result);
    return result;
}

std::vector<int> getVectorWithEvenNumbers(size_t numberOfElements) {

    // Limit the number of elements to the correct range
    numberOfElements = std::clamp(numberOfElements, MinNumberElementsInVector, MaxNumberElementsInVector);

    // Resulting vector. Reserve space for "numberOfElements" numbers
    std::vector<int> result(numberOfElements);

    // Get numbers from user
    for (bool allEven = false; !allEven; ) {

        // Give info for user
        std::cout << "\n\nPlease enter " << numberOfElements << " even numbers:\n";

        // Read all values from user
        std::copy_n(std::istream_iterator<int>(std::cin), numberOfElements, result.begin());

        // Check, if all values are even

        allEven = std::all_of(result.begin(), result.end(), [](const int i) {return (i % 2) == 0; });

        // Error message, in case of odd values
        if (!allEven) std::cout << "\n\nError during input. Try Again.\n\n";
    }
    return result;
}

void halfMaxValues(std::vector<int>& values) {
    // Search max value
    std::vector<int>::iterator max = std::max_element(values.begin(), values.end());
    if ((max != values.end()) && ((*max > 2) || (*max < -2))) {
        int m = *max;
        // Half all found max values, if even
        std::for_each(values.begin(), values.end(), [&m](int& i) {if ((i % 2 == 0) && (i == m)) {i /= 2;}});
    }
}

// Show contents of vector on screen
inline void displayVector(std::vector<int> values) {
    std::cout << "\nResult:\n";
    std::copy(values.begin(), values.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << "\n";
}

int main() {

    // Get number of elements for our vector
    size_t numberOfVectorElements{ getNumberOfVectorElements() };

    // Get the elements and put them into the vector
    std::vector<int> values{ getVectorWithEvenNumbers(numberOfVectorElements) };

    // How many times should we perfom the action
    size_t numberOfActions{ getNumberOfActions() };

    while (numberOfActions-- && !std::all_of(values.begin(), values.end(), [](int i) {return (i == 2) || (i == -2) || (i % 2 == 1); })) {
        halfMaxValues(values);
        displayVector(values);
    }
}

【讨论】:

  • 谢谢,但正如我所说,我们还没有研究过向量和算法,所以我们不能使用它们
【解决方案2】:

这是另一个使用 std::vector 代替原始整数数组的示例:

#include <algorithm>
#include <iostream>
#include <vector>

void read_items(std::vector<int> &v)
{
    int i = 0;
    int nitems = v.size();
    while( i < nitems ) {
        std::cout << "Enter number: ";
        std::cin >> v[i];
        if (v[i] < 2) {
            std::cout << "Error: number has to be larger or equal to 2!\n";
        }
        else if (v[i] % 2 != 0) {
            std::cout << "Error: enter even numbers only!\n";
        }
        else {
            i++;
        }
    }
}
void print_vector(const std::vector<int> &v) {
    std::cout << "v: ";
    for (auto &item : v ) {
        std::cout << item << " ";
    }
    std::cout << '\n';
}

int main ()
{

    std::cout << "How many numbers would you like to type? ";
    int nitems;
    std::cin >> nitems;

    if(nitems<4 || nitems>1024) {
        std::cout << "Invalid input!\n";
        return 1;
    }
    std::vector<int> v(nitems);

    read_items(v);
    print_vector(v);

    // how many times u have to find the biggest num and half it
    std::cout << "A<num>, enter a number: ";
    int numa;
    std::cin >> numa;
    for (int k = 0; k < numa; k++) {
        int max = *std::max_element(v.begin(), v.end());
        for(int  j = 1; j < nitems; j++) {
            if(v[j] == max)
                v[j] /= 2;
        }
        print_vector(v);
    }

    return 0;
}

【讨论】:

  • 谢谢,但我们没有研究过向量,所以我们不能使用它们
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-23
  • 1970-01-01
  • 2020-01-28
  • 1970-01-01
  • 2017-02-27
  • 2017-12-14
  • 2023-02-20
相关资源
最近更新 更多