【问题标题】:Given sequence of integers a(1),a(2), a(n). Create a new sequence through replacing all a(i) by 1, if |a(i)=max (a(1),a(2),a(n)); or by 0 otherwise给定整数序列 a(1),a(2),a(n)。如果 |a(i)=max (a(1),a(2),a(n)); 通过将所有 a(i) 替换为 1 来创建一个新序列;否则为 0
【发布时间】:2021-12-27 09:20:40
【问题描述】:

我已经有了一些代码,但是我的讲师告诉我它只比较数组中的第一个整数,负数没有考虑

#include <iostream>
using namespace std;
int main() {
    int max, n, check;    //declaring variables
    check = 1;
    while (check == 1) {     //programm executes repitedly
        cout << "Enter array element count: ";
        cin >> n;             //user inputs number of elements in array
        if (n <= 0)            //check that number should be bigger then 0
            cout << "Please enter number greater then 0";
        int array[n];           //declaring an array
        for (int i = 0; i < n; i++) {      //entering numbers to array
            cout << "Enter number: ";
            cin >> array[i];
            if (max < array[i]) {            //assigning the biggest number of array as max
                max = array[i];
            }
        }
        for (int i = 0; i < n; i++) {      //assigning value to max==1
            if (array[i] == max) {
                array[i] = 1;
            }
            else {                            // to other value assigning 0
                array[i] = 0;
            }
            cout << array[i];                   //showing the results
        }
        cout << "\n1 - continue, 0 - end\n";
        cin >> check;
    }
}

【问题讨论】:

  • 那么,您的讲师有准确的错误描述吗?为什么不解决这个问题?另外,请提供一个minimal reproducible example(大部分都可以,仍然需要手动输入),它的格式与预期和实际结果一致(不可以)。作为这里的新用户,也可以使用tour 并阅读How to Ask
  • VLA int array[n]; 不是有效的 C++,请改用 std::vector
  • 您的讲师的评论很奇怪,因为与当前代码不匹配,但 max 未初始化,导致 UB。

标签: c++ arrays


【解决方案1】:

我们随时为您提供帮助。

所以让我首先尝试编译您的代码。这是我的 C++ 编译器的结果:

所以,我们现在已经可以看到几件事情了。 VLA(可变长度数组)int array[n]是无效的 C++ 代码。 VLA 不是 C++ 语言的一部分,不能使用。此外,编译器显示了未初始化的 varaibale `max' 的问题。如果 may 没有值,那么你的程序的行为是未定义的。

强烈推荐。请始终打开所有编译器警告。示例:-Werror -Wall -Wpedantic。并修复所有警告。

好的,让我们尝试摆脱这些问题。首先是 VLA。 VLA 始终可以替换为std::vector。这是一个动态数组,可以根据需要增长。但后来我经常听到学生说他们没有了解vector。这基本上意味着老师应该被解雇,但也许首先教学生使用原始指针用于拥有的内存和new,这在C++中基本上是禁止的,这可能是一个战略决定。但是,好的,让我们使用这种方法。最后不要忘记删除分配的内存。

并且必须初始化变量“max”。我们将在此处使用可能的最小值,以便我们可以确保其他所有内容都将大于此初始值。

在标题&lt;limits&gt; 中,我们可以找到我们需要的所有内容。请看here

结果是这个已经在运行的程序:

#include <iostream>
#include <limits>
using namespace std;
int main() {
    int max=std::numeric_limits<int>::min(), n, check;    //declaring variables
    check = 1;
    while (check == 1) {     //programm executes repitedly
        cout << "Enter array element count: ";
        cin >> n;             //user inputs number of elements in array
        if (n <= 0)            //check that number should be bigger then 0
            cout << "Please enter number greater then 0";
        int *array = new int[n];           //declaring an array
        for (int i = 0; i < n; i++) {      //entering numbers to array
            cout << "Enter number: ";
            cin >> array[i];
            if (max < array[i]) {            //assigning the biggest number of array as max
                max = array[i];
            }
        }
        for (int i = 0; i < n; i++) {      //assigning value to max==1
            if (array[i] == max) {
                array[i] = 1;
            }
            else {                            // to other value assigning 0
                array[i] = 0;
            }
            cout << array[i];                   //showing the results
        }
        cout << "\n1 - continue, 0 - end\n";
        cin >> check;
        delete[] array;
    }
}

还有很多事情需要检查。特别是对 unser 输入的验证很重要。更强大的版本是:

#include <iostream>
#include <limits>

int main() {

    // We will rund the program until somebody sets this variable to false
    bool runProgram = true;
    while (runProgram) {

        // Instruction to use, to enter the number of elements to check
        std::cout << "\nEnter array element count: ";

        // Get the number of elements and check, if the we got a valid number
        unsigned int arrayElementCount = 0;
        if ((std::cin >> arrayElementCount) and (arrayElementCount > 0u)) {

            // OK we got a valid number. Now allocate memory for our array.
            int* array = new int[arrayElementCount];

            // We want to find the max value for all values. Therefore we will initialie the initial value with min
            int max = std::numeric_limits<int>::min();

            // In a loop, get user input, store in array and check for max
            for (unsigned int i = 0; i < arrayElementCount; ++i) {      

                // We want to check, if the user enters a valid number or some nonesend like "abc"
                // So, we will read as long the number is not valid
                bool numberIsValid = false;
                while (not numberIsValid) {

                    // Instruction to user to enter number i
                    std::cout << "Enter number '" << i + 1 << "' :\t";

                    // Try to read a valid number
                    if (std::cin >> array[i]) {

                        // Oke, noe we have a valid number. We do not need to read again
                        numberIsValid = true;

                        // CHeck for a new maximum
                        if (max < array[i]) {     
                            max = array[i];
                        }
                    }
                    else {
                        // We got a bad number. std::cin is in error state and the input buffer contains garbage
                        // Show error message
                        std::cerr << "\n*** Error: Invalid input. Please try again\n\n";
                        std::cin.clear(); // Reset error flages of std::cin and remove still existing garbage from the input buffer
                        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
                    }
                }
            }
            // We want to show the result
            std::cout << "\n\nResult:\n\n";
            for (unsigned int i = 0; i < arrayElementCount; i++) {

                // For a max value we will write a 1 to our array
                if (array[i] == max) {
                    array[i] = 1;
                }
                else {                            
                    // To other value assign a 0
                    array[i] = 0;
                }
                // And output restult
                std::cout << array[i] << ' ';                   
            }

            // Ask user, if he wants to continue
            std::cout << "\n\n\n1 - continue program, 0 - end program\n";

            // Get decision of user
            int check = 0;
            // In case of error or other input than 1, end program
            if (not (std::cin >> check) or (check != 1))
                runProgram = false;

            // Release previously allocated memory
            delete[] array;
        }
        else {
            // Error while getting the number of elements for the array
            std::cerr << "\n*** Error: Problem with the input of the element count\n\n";
            std::cin.clear();// Reset error flags of std::cin and remove still existing garbage from the input buffer
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
    }
}

如有问题,请在评论中提问

【讨论】:

  • 非常感谢您的及时回复。我有一个问题 - 如果我输入 -7,5,7 我会得到 101(这意味着负值转换为正值,我们使用的是 -7 的模块,即 7)
  • 对不起,我不太明白。我发布的程序显示 0 0 1 作为 -7、5、7 的输出。还是您希望得到 1 0 1 作为输出。在这种情况下,您需要写if (std::abs(array[i]) == max) {。但是,我不确定你的意思。 . .
  • 是的,我希望得到 1 0 1 的输出,我可以使用这段代码吗?
  • if(array[i]
  • 是的,当然。但是你可以保存if。编写`array[i] = abs(array[i]); ` 足够了
猜你喜欢
  • 1970-01-01
  • 2014-12-29
  • 2015-08-26
  • 1970-01-01
  • 2017-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-03
相关资源
最近更新 更多