[英]C++ counting number of positive/negative numbers from an array
我正在尝试创建一个代码,该代码使用函数计算给定数组中正数和负数的数量。 例如,在数组{-1, 2, -3, 4.5 , 0, .3, -999.99}
它应该显示 2 个正数和 4 个负数并排除数字 0。
我正在使用两个计数器来跟踪有多少负数和正数,一个 for 循环来循环遍历数组,但是当调用 true 或 false 以显示正确的计数器时,我不知道如何合并布尔参数.
我的代码没有输出正确的信息,任何提示都有助于改进我的代码。
#include <iostream>
using namespace std;
int countingArray(float list[], int size, bool)
{
int NumberOfPositives = 0;
int NumberOfNegatives = 0;
for (int index = 0; index < size; index++) {
if (list[index] > 0) {
if (true) {
NumberOfPositives++;
}
}
else if (list[index] < 0) {
if (false) {
NumberOfNegatives++;
}
}
else if (list[index] == 0)
continue;
}
return NumberOfPositives;
return NumberOfNegatives;
}
int main()
{
float list[] = { -1, 2, -3, 4.5, 0, -3, -999.99 };
cout << "# of Pos. = " << countingArray(list, 7, true) << endl;
cout << "# of Pos. = " << countingArray(list, 7, false) << endl;
system("PAUSE");
return 0;
}
您不能return
2 个值。 一旦return
,该函数立即结束。 因此,countingArray 只会返回您拥有的正数的数量,因为return NumberOfPositives
发生在return NumberOfNegatives
之前。
我会这样写:
void countingArray(float list[], int size, int& positive, int& negative) {
for (int index = 0; index < size; index++)
if (list[index] > 0)
++positive;
else if (list[index] < 0)
++negative;
}
int main() {
float list[] = { -1, 2, -3, 4.5, 0, -3, -999.99 };
int positive = 0;
int negative = 0;
countingArray(list, 7, positive, negative);
cout << "# of Pos. = " << positive << endl;
cout << "# of Pos. = " << negative << endl;
system("PAUSE");
return 0;
}
通过引用传递计数器,这样你就不会循环数组两次。 你的问题是你从你的函数返回两次,如果你需要在返回之前检查布尔标志并根据你的标志返回正数或负数计数器。
此外,您可以使用 std::array 代替 c 类型数组,这样您就可以使用迭代器遍历数组,而无需传递数组大小。
像这样的事情会做到:
#include <iostream>
struct PosNeg
{
void reset()
{
p = n = z = 0;
}
int p; // Positive.
int n; // Negative.
int z; // Zero.
};
void pos_neg(float* arr, int sz, PosNeg& count)
{
for (int i = 0; i < sz; ++i)
{
if (arr[i] < 0)
{
count.n++;
}
else if (arr[i] == 0)
{
count.z++;
}
else
{
count.p++;
}
}
}
int main()
{
float arr[] = { 1.0f, 2.0f, 3.0f, 0.0f, -1.0f, -2.0f, -3.0f };
PosNeg pn;
pn.reset();
pos_neg(arr, 7, pn);
std::cout << "Pos: " << pn.p << " Neg: " << pn.n << " Zero: " << pn.z << "\n";
std::cin.get();
return 0;
}
将所有内容都包含在一个结构中,并计算正数、负数,最终为 0。
请记住,在使用之前必须将结构的每个成员设置为零(初始化时默认为随机)。
你可能会这样做,标准:
std::pair<std::size_t, std::size_t> countingNegPos(const float* v, std::size_t size)
{
return { std::count_if(v, v + size, [](auto f){ return f < 0; }),
std::count_if(v, v + size, [](auto f){ return f > 0; })};
}
int main()
{
const float list[] = { -1, 2, -3, 4.5, 0, -3, -999.99 };
auto [neg, pos] = countingArray(list, 7);
std::cout << "# of Neg. = " << neg << std::endl;
std::cout << "# of Pos. = " << pos << std::endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.