[英]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.