【发布时间】:2021-06-06 22:01:38
【问题描述】:
我从昨天开始就一直在尝试解决这个问题。程序应该接受来自用户的 N 个数字并将它们放在一个数组中。我已经做到了。但是,我似乎不知道如何“警告”用户输入重复并让用户再次输入。 这是我的代码:
# include <iostream>
using namespace std;
int main () {
int N, pos = -1, arr [N], i, j;
int startLoop = 1;
// the 'startLoop' variable is used so that the first user input can have the break function
bool found = false;
while (startLoop != 0) {
cout << "Enter the number of integers to be entered: ";
cin >> N;
if (N <= 4) {
cout << "Invalid. \n";
}
if (N > 4) {
cout << "\n\nEnter " << N << " unique numbers: " ;
for (i = 0; i < N; i++) {
cin >> arr [i];
for (j = 0; j < N && !found; j++) {
if (arr [j] == arr [i]) {
found = true;
cout << "Enter again: ";
}
}
break;
}
}
}
【问题讨论】:
-
首先,您使用的是非标准 C++ 的 VLA,并且您没有正确使用它。
-
看起来你已经实现了一些东西 (
found) 来检查是否有重复。不要说“代码不起作用”,而是解释代码到底出了什么问题(输入是什么,当前的输出是什么,有什么问题?) -
要检查数组中是否存在元素,您可以使用std::find function
-
两个非常强大的高级规则(它们似乎从未在 CompSci 课程中教授过):1) 尽可能独立开发新功能,2) 解决一个更简单的问题。在这种情况下,尝试编写要求 N 个数字但拒绝接受“13”的代码。并编写一个函数来测试一个给定的数字 k 在数组的前 j 个元素中。
-
int N, pos = -1, arr [N], i, j;是非标准和UB,不是吗?
标签: c++ arrays duplicates user-input