程序与数组来检查增加/减少的数字
Program With Array To Check For Increasing/Decreasing Numbers
初学c++的学生在这里开始学习使用数组的不同方法。我正试着把下面的程序放在一起。它应该要求用户输入一组数字,这些数字将进入一个数组。这组数字可以在用户想要的任何点增加或减少。
例如:1 2 3 4 9 8 7 4 5 6 10 11 12 20 19 18 17
程序将根据这组数字进行检查,并说明每次增加或减少的原因。现在程序将返回"增加"或"减少"。
例如,根据它返回的上述数字集运行它:
增加减少减少
然而,我有两个问题:
我认为它不能正确地解释数组中发生的所有变化(增加和减少)。
我现在必须返回发生的变化的数量,而不是"减少"/"增加"。也就是说,在上面的例子中,它将返回"3",因为有1个真值和2个假值。
如果有人能提出建议,我将非常感激。
非常感谢!!
#include <iostream>
using namespace std;
bool increasing(int arr[], int n);
int main()
{
int arr[20], n;
cout << "Enter a set of Increasing/Decreasing numbers (ex. 1 2 3 6 5 4 7 8 9 3 2 1)." << endl;
cout << "Press 'Enter' to see results" << endl;
while (cin >> n)
{
for (int i = 0; i <= n; i++)
{
cin >> arr[i];
}
cout << (increasing(arr, n) ? "increasing" : "decreasing") << endl;
}
return 0;
}
bool increasing(int arr[], int n)
{
int x = 0;
for (int i = 0; i < n - 1; i++)
{
if (arr[i] < arr[i + 1])
{
x++;
}
}
if (x == n - 1)
{
return true;
}
else
{
return false;
}
}
供1。你必须多次调用increasing
函数。因此,您还需要一个整数advance
来记住您的进度。
bool increasing(int arr[], int& advance, int n);
你可以用(x
counts the number of increase,如2所述)
int advance = 0;
do {
int x = 0;
cout << (increasing(arr, advance, n, x) ? "increasing " : "decreasing ") << x << endl;
} while (advance < n-1);
你可以用
实现它bool increasing(int arr[], int& advance, int n, int& x)
{ assert(advance < n-1);
x = 0;
bool doesIncrease = arr[advance] < arr[advance + 1];
bool isStable = arr[advance] == arr[advance + 1];
if (doesIncrease) {
for (int i = advance+1; i < n - 1; i++)
{
if (arr[i] < arr[i + 1])
{
x++;
}
}
}
else if (isStable) {
...
}
else { // decreasing
for (int i = advance+1; i < n - 1; i++)
{
if (arr[i] > arr[i + 1])
{
x++;
}
}
};
return doesIncrease;
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 数组索引的值没有增加
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 为什么我的代码在输出中增加了93天
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 在C++中增加大数字(近 100.000 位)
- 有效数字在增加
- 如何设置QSqlQueryModel的Qt::Vertical headerData在进行分页时增加数字
- 在c或c++中,将字母数字字符串abcd1234增加到abcd2000
- 增加递归函数中的数字
- 为什么每次运行程序时,我的"随机"生成的数字都在增加?
- 无法在C++中增加程序中的数字范围
- 程序与数组来检查增加/减少的数字
- 为什么 C++ 中的编译器不增加循环中最后一个数字的值?
- 如何增加一个数字,停止它,在C++上使用 if/else 语句