gpt4 book ai didi

c++ - 如何使用数组解决这个问题?

转载 作者:行者123 更新时间:2023-12-04 00:49:38 25 4
gpt4 key购买 nike

我是编程新手,有办法解决这个问题吗:

Take 10 integer inputs from user and print the following

  1. number of positive numbers.
  2. number of negative numbers.
  3. number of odd numbers.
  4. number of even numbers
#include <iostream>
using namespace std;

int main()
{
int numArray[10];

cout<<"Enter Number :";
for(int i=0; i<10; i++)
{
cin>>numArray[i];
}

for(int i=0; i<numArray[i]; i++)
{
if(numArray[i]>0)
{
cout<<"Positive Number "<<numArray[i] <<endl;
}
else
{
cout<<"Negative Number "<<numArray[i]<<endl;
}

if(numArray[i]%2==0)
{
cout<<"Odd number "<<numArray[i]<<endl;
}
else
{
cout<<"even number "<<numArray[i]<<endl;
}

}

return 0;
}

最佳答案

你可以在没有数组的情况下做到这一点,但为了清楚起见,我只是坚持你的初衷。

#include <iostream>
#include <array>
using namespace std;

int main()
{
array<int, 10> numArray; //an array of ints, size 10. this is CPP style array, it is 'safer' than C-style array. (someone correct me)

//get your 10 inputs.
cout << "Enter Number :";
for(size_t i = 0; i < numArray.size(); i++)
{
cin >> numArray[i];
}

int positive_count = 0;
int negative_count = 0;
int even_count = 0;
int odd_count = 0;

//loop thru your 10 inputs, increment counters accordingly.
for(size_t i = 0; i < numArray.size(); i++)
{

if (numArray[i] < 0)
{
negative_count += 1;
}
if (numArray[i] > 0)
{
positive_count += 1;
}

if (numArray[i] % 2 == 0)
{
even_count += 1;
}
else
{
odd_count += 1;
}

}

cout << "Positive Number " << positive_count << endl;
cout << "Negative Number " << negative_count << endl;

cout << "even number " << even_count << endl;
cout << "Odd number " << odd_count << endl;

return 0;

}

关于c++ - 如何使用数组解决这个问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67559176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com