初学者数组的问题,C++
Problems with Beginner Arrays, C++
赋值需要三个函数。用户输入数字 0-9,直到输入 10,这将停止输入,并计算每个数字,然后输出每个数字中有多少个已计数。仅当用户为其输入数字时,它才应输出。
我唯一的问题是,对于数组中用户不使用的每个元素,Xcode 都会将其计为 0,因此最终输出具有异常大量的零。其他一切正常。
这是我的代码
#include <iostream>
using namespace std;
// counter function prototype
void count(int[], int, int []);
// print function prototype
void print(int []);
int main()
{
// define variables and initialize arrays
const int SIZE=100;
int numbers[SIZE], counter[10], input;
// for loop to set all counter elements to 0
for (int assign = 0; assign < 10; assign++)
{
counter[assign]=0;
}
// for loop to collect data
for (int index=0 ; input != 10 ; index++)
{
cout << "Enter a number 0-9, or 10 to terminate: ";
cin >> input;
// while loop to ensure input is 0-10
while (input < 0 || input > 10)
{
cout << "Invalid, please enter 0-9 or 10 to terminate: ";
cin >> input;
}
// if statements to sort input
if (input >= 0 && input <=9)
{
numbers[index] = input;
}
}
// call count function
count(numbers, SIZE, counter);
// call print function
print(counter);
return 0;
}
// counter function
void count(int numbers[], int SIZE, int counter[])
{
// for loop of counter
for (int index = 0 ; index < 10 ; index++)
{
// for loop of numbers
for (int tracker=0 ; tracker < SIZE ; tracker++)
{
// if statement to count each number
if (index == numbers[tracker])
{
counter[index]++;
}
}
}
return;
}
// print function
void print(int counter[])
{
// for loop to print each element
for (int index=0 ; index < 10 ; index++)
{
// if statement to only print numbers that were entered
if (counter[index] > 0)
{
cout << "You entered " << counter[index] << ", " << index << "(s)" << endl;
}
}
return;
}
你所说的"XCode count[ing] as a 0"实际上只是未初始化的值。鉴于您决定将用户的输入限制为 0-9,解决此难题的一种简单方法是,在调整数组大小后立即循环访问数组并将每个值设置为 -1。
此后,当用户完成输入时,不要只cout
每个值,而只需使用如下所示的条件打印它:
if (counter[index] != -1)
{
cout << "You entered " << counter[index] << ", " << index << "(s)" << endl;
}
请注意,这种用例更适合链表或向量之类的东西。就目前而言,您没有做任何事情来调整数组大小或防止溢出,因此如果用户尝试输入超过 100 个数字,您会遇到严重的问题。
首先,这不是对你的确切问题的答案,而是关于如何以更简单的形式编写代码的建议。
我不会为你写这个,因为这是一个任务,而且相当简单。就编码而言,看起来您对事情有很好的处理。
考虑一下:
您需要允许用户输入 0-10,并计算所有 0-9。数组有索引,数组 10 的整数将保存您按索引计数的 10 个数字。现在你只有一些空的int
坐在那里,所以为什么不用它们来计数呢?
代码提示:
++numbers[input];
第二个提示:不要忘记将所有内容初始化为零。
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 基于boost的程序的静态链接——zlib问题
- C++格式化输出问题
- 使用mongocxx驱动程序时包含头文件问题