![](/img/trans.png)
[英]Why is my Binary Search Tree void remove function not working properly?
[英]Why is my function not working properly
我檢查向量中數字是否為偶數或奇數的函數無法正常工作。 此功能將打印我在矢量中鍵入的數字,並將其分為EVENS / ODDS 2類。 但是,如果我有一個負數,則可能無法打印而不是正常工作。 有問題的代碼在這里:
void printEvensAndOddsVector(const vector <int>& new_v1)
{
cout << "Vector Evens: ";
for (unsigned int i = 0; i < new_v1.size(); ++i)
{
if (new_v1.at(i) % 2 == 0)
{
cout << new_v1.at(i) << " ";
}
}
cout << " \n";
cout << "Vector Odds: ";
for (unsigned int i = 0; i < new_v1.size(); ++i)
{
if (new_v1.at(i) % 2 == 1) // Here is the problem.
{
cout << new_v1.at(i) << " ";
}
}
cout << " \n";
}
或者更確切地說,這行代碼: if (new_v1.at(i) % 2 == 1)
它打印出奇數,但只輸出正數而不是負數。 但是如果我將其更改為if (new_v1.at(i) % 2 != 0)
那么它將正常工作。 為什么會發生這種情況,並且等號運算符有問題嗎? 如果是,那么為什么在使用等號運算符的情況下即使偶數為負數也要打印偶數?
代碼在這里供參考。
clude <iostream>
#include <vector>
using namespace std;
void fillVector(vector <int>&);
void printVector(const vector <int>&);
void printEvensAndOddsVector(const vector <int>&); // Prints Evens and Odds.
int main()
{
vector <int> v1;
fillVector(v1);
printVector(v1);
printEvensAndOddsVector(v1);
cout << "\n\n\n";
system( "pause");
return 0;
}
// Function Definitions
void fillVector(vector <int>& new_v1)
{
int number;
cout << "Type in numbers and type -100 to stop: ";
cin >> number;
while (number != -100)
{
new_v1.push_back(number);
cin >> number;
}
}
void printVector(const vector <int>& new_v1)
{
cout << "\nVector: ";
for (unsigned int i = 0; i < new_v1.size(); ++i)
{
cout << new_v1.at(i) << " ";
}
cout << " \n";
}
void printEvensAndOddsVector(const vector <int>& new_v1)
{
cout << "Vector Evens: ";
for (unsigned int i = 0; i < new_v1.size(); ++i)
{
if (new_v1.at(i) % 2 == 0)
{
cout << new_v1.at(i) << " ";
}
}
cout << " \n";
cout << "Vector Odds: ";
for (unsigned int i = 0; i < new_v1.size(); ++i)
{
if (new_v1.at(i) % 2 == 1)
{
cout << new_v1.at(i) << " ";
}
}
cout << " \n";
}
這行代碼:
if (new_v1.at(i) % 2 == 1)
。 它打印出奇數,但只打印正數,而不打印負數。
對於負數n
, n % 2
在C ++中返回0
或-1
。 它永遠不會返回1
,因此條件對於負輸入不能成立。
正如您所發現的,比較零是可行的。
請參見具有負值的模運算符
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.