您好,我需要有关C ++程序的帮助。 [英] Hello, I need help with a C++ program.

查看:106
本文介绍了您好,我需要有关C ++程序的帮助。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个程序,其输出应该是这样的,数组的每个第一个元素都是1,每个第二个元素是0.我需要检查数组中的元素是否为奇数然后打印出1并且如果是元素是奇数然后打印出来0.我需要在条件中检查这个条件。就像有限状态机一样。我没有这样做。任何帮助将不胜感激。



我尝试过:



I need to write a program, Whose output should be like, every first element of an array is 1 and every second element is 0. I need to check in the array if the element is odd then print out 1 and if the element is odd then print out 0. I need to check this condition in if condition.Just like Finite state machine. I am failing in doing so. Any help would be appreciated.

What I have tried:

using namespace std;

int main(){
	
	cout<<"Enter the size of array"<<"\n";
	
	int n,i;
	cin>>n;
	int array[n];
	for( i=0; i<n;i++){
	if(array[i] % 2!=0 && array[i] % 2==0){
		
	}
	cout<<"1,0";
			
}

}

推荐答案

另请参阅我的评论。假设您需要为奇数打印1而对偶数打印0,如果,则甚至不需要



这是因为

1%2结果1

2%2结果0

3%2结果为1

4%2结果0

...依此类推。咨询例如维基有关模数运算符的详细信息。





版本I 检查数组值

现在我不熟悉 cout 但这样的事情应该可以胜任:

See also my comments. Assuming you Need to print "1" for odd numbers and "0" for even number you don't even Need an if.

This because
1 % 2 results in 1
2 % 2 results in 0
3 % 2 results in 1
4 % 2 results in 0
... and so on. Consult e.g. wiki for detailed Information about the Modulo Operator.


Version I Check Array values
Now I'm not familar with cout but something like this should do the job:
for(i= 0; i < n; i++)
{
   cout << array[i] % 2;
}







版本II 检查索引




Version II Check index

for(i= 0; i < n; i++)
{
   cout << i % 2;
}







版本III 检查索引'




Version III Check index'

for(i= 0; i < n; i++)
{
   cout << (i + 1) % 2;
}





注意:请记住理查德MacCutchan - 专业档案 [ ^ ]:你的主要问题是你永远不会在数组中输入任何值。



Note: Keep in mind the comment of Richard MacCutchan - Professional Profile[^] : "Your main problem is that you never enter any values into the array."

如果要输入数组大小,则需要分配动态内存。

When you want to enter the array size you need to allocate dynamic memory.
int *array = new int[n];
//work it 
delete array;

你需要一个循环来填充数组。



提示:在操作中使用大括号以提高清晰度并避免错误。

And you need a loop to fill the array.

Tip: use braces in your operations for clarity and avoiding bugs.


这篇关于您好,我需要有关C ++程序的帮助。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆