c ++计数来自数组的正/负数数 我正在尝试创建一个代码,该代码使用一个函数计算给定数组中的正数和负数数。例如,在数组{-1、2,-3、4.5、0,.3,-999.99}中应该...

问题描述 投票:0回答:3

你不能2个值。一旦您
#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; }

,该功能立即结束。 因此,CountingArray只会返回您拥有的正数,因为

return

return

.
之前发生。
    
c++ arrays function
3个回答
5
投票
我会这样写:

return NumberOfPositives
通过参考使计数器通过柜台,以免两次循环阵列。
而且您的问题是,您需要从功能中返回两次,如果您的方式进行操作,则需要在返回并根据您的标志返回正面或负面计数器之前检查布尔旗。

此外,您可以使用std ::数组而不是C键入数组,这样您就可以使用迭代器循环循环,而无需传递数组大小。

像这样的东西会做到这一点:
return NumberOfNegatives

compass所有物体成结构,并计算正数,负数和最终0.

2
投票
记住,您必须在使用它之前将结构的每个成员设置为零(默认情况下随机启动时,初始化时)。

您可能会做的,用std:
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;
    }

使用C ++ 20:

1
投票
#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; }


最新问题
© www.soinside.com 2019 - 2025. All rights reserved.