【发布时间】:2015-06-08 23:07:48
【问题描述】:
我有一个作业要求程序从用户输入中读取 20 个数字到一个数组中。 条件要求该值在 10-100 之间且不重复。我也只能使用一个包含 20 个元素的数组。但是,它不应该提示用户并且根本不存储值;最后,程序必须打印出唯一的用户值。 正确的结果例如:
input = 9 10 15 15 15 0
output = 10 15
//this is a small example with a 6 element array instead of 20
当我测试我的程序时,我只会得到
input: 9 10 15 15 15 0
output: 10 15 15 15
//this is a small example with a 6 element array instead of 20
我使用基于范围的循环编写代码来检查值,如果不满足条件,则将值设置为 0。所以任何不为零的东西都不会被打印出来。我已经解决了有关堆栈溢出的所有问题,但找不到具体问题的答案:
- 如何使用类构造函数将所有数组元素初始化为零。
- 将其设为“静态”,这样当我运行另一个函数时,先前的数组值是全局的,并由用户输入维护。
-
我创建的循环似乎有问题,但看起来很完美。我和同学们商量了一下,他们也同意了。
//arrayinput.h #include <array> #include <string> class arrayelimination { public: const static size_t limit = 20; arrayelimination(); void inputArray(); void displayArray(); private: std::array < int , limit > store; int userinput; }; //arrayinput.cpp #include <iostream> #include <array> #include "arrayinput.h" using namespace std; arrayelimination::arrayelimination() { array < int , limit> store = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; } void arrayelimination::inputArray() { for ( size_t i = 0; i < store.size(); i++) { cout << "Enter number between 10-100 for array box [" << i << "]: " ; cin >> userinput; //check if numbers is between 10-100 if (userinput >= 10 && userinput <= 100) { //MOST LIKELY ERROR check if number has previously been used. for ( int &check : store) { if ( check != userinput) { store[i] = userinput; break; } else store[i] = 0; } } //output if number isn't between 10-100 else store[i] = 0; } } void arrayelimination::displayArray() { cout << "Your unique array numbers stored include...\n"; //output all the unique numbers that the user inputted. for ( size_t j = 0; j < 20; j++) { //if the value is NOT 0, output. if (store[j] != 0) { cout << "array[ " << j << " ] = " << store[j] << "\n"; } } }
当我测试我的程序时,我只会得到
input: 10 15 15 15 2 0 0 0 0 0 0 0 ... 0
output: 10 15 15 15
将其设置为零的概念有效,但重复值不是唯一的。
我必须使用面向对象的设计作为这项作业的要求。我接近死胡同我真的不知道这是如何工作的。请帮帮我。
PS:我的错我忘了说我只能使用一个数组
【问题讨论】: