我有一个问题,我有这段代码,当我运行它时,代码启动并告诉我输入数字,但是当我输入它们时,没有任何反应 代码应该显示除以 2 的元素从向量中得到 0,但它没有做任何事情(nu sunt elemente pare 意味着没有除以 2 的元素得到 0.....并且 numbere pare表示除以 2 的元素得到 0
我期望这两个给我向量中可以被 2 整除的元素,但是代码没有给我它们 这是代码:
#include <iostream>
using namespace std; int n,i,a[100],t;
int main()
{
cout << "n="; cin>>n;
i=1;
do{
cin>>a[i];
if(a[i]%2==0)t++;
}while(i<n||i==n);
i++;
if(t==0){
cout<<"Nu sunt elemente pare.";
}else cout<<t<<" numere pare";
return 0;
}
只是为了向您展示当前的 C++ 编写方式通常与您现在正在学习的不同。
#include <iostream>
#include <vector>
#include <algorithm>
// using namespace std; No don't do this.
// learn to make functions for substeps
std::vector<int> ask_for_values()
{
int count;
std::cout << "Enter number of values : ";
std::cin >> count;
std::vector<int> values(count,0);
// range based for loop
// reading each value from std::cin
for(auto& value : values)
{
std::cout << "Enter a value : ";
std::cin >> value;
}
return values;
}
// declare a predicate for odd
// again an extra function helps you describe your intent in code
bool is_odd(int value)
{
return (value % 2) == 1;
}
int main()
{
//std::vector values = ask_for_values();
std::vector values{1,2,5,4,3,9}; // test values
//don't be afraid to use long variable names ;)
//std::count_if counts the number of elements for which the predicate holds.
auto number_of_odd_numbers = std::count_if(values.begin(), values.end(), is_odd );
std::cout << "Number of odd numbers = " << number_of_odd_numbers<< "\n";
return 0;
}