C++ 打印奇数程序

编写一个 C++ 程序,从 0 到给定值打印奇数。此 C++ 程序允许用户输入任何整数。接下来,我们使用 for 循环迭代从 1 到用户给定值的数字。在循环中,我们使用 If 语句检查 ( i % 2 != 0 )。如果为真,则将 i 值打印为奇数。

#include<iostream>
using namespace std;

int main()
{
	int number;
	
	cout << "\nPlease Enter Maximum limit Value to print Odd Numbers =  ";
	cin >> number;
	
	cout << "\nList of Odd Numbers from 1 to " << number << " are\n"; 
	for(int i = 1; i <= number; i++)
  	{
  		if ( i % 2 != 0 )
  		{
  			cout << i <<" ";
		}	
  	}
		
 	return 0;
}
Please Enter Maximum limit Value to print Odd Numbers =  10

List of Odd Numbers from 1 to 10 are
1 3 5 7 9 

在此 C++ 奇数返回程序中,我们修改了 for 循环以删除 If 语句。在这里,我们将 i 值增加了 2(而不是 1)。这样,从 1 开始,每隔两个数字都会是奇数。

#include<iostream>
using namespace std;

int main()
{
	int number;
	
	cout << "\nPlease Enter Maximum limit Value to print Odd Numbers =  ";
	cin >> number;
	
	cout << "\nList of Odd Numbers from 1 to " << number << " are\n"; 
	for(int i = 1; i <= number; i = i + 2)
  	{
  		cout << i <<" ";
  	}
		
 	return 0;
}
Please Enter Maximum limit Value to print Odd Numbers =  24

List of Odd Numbers from 1 to 24 are
1 3 5 7 9 11 13 15 17 19 21 23 

使用 While 循环打印奇数的 C++ 程序

#include<iostream>
using namespace std;

int main()
{
	int number, i = 1;
	
	cout << "\nPlease Enter Maximum limit Value to print Odd Numbers =  ";
	cin >> number;
	
	cout << "\nList of Odd Numbers from 1 to " << number << " are\n"; 
	while(i <= number)
  	{
  		cout << i <<" ";
  		i = i + 2;
  	}
		
 	return 0;
}
Please Enter Maximum limit Value to print Odd Numbers =  32

List of Odd Numbers from 1 to 32 are
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 

这个 C++ 打印奇数示例允许输入最小值和最大值。接下来,它打印从最小值到最大值之间的奇数。

#include<iostream>
using namespace std;

int main()
{
	int minimumOdd, maximum;
	
	cout << "\nPlease Enter Minimum limit Value to print Odd Numbers =  ";
	cin >> minimumOdd;
	
	cout << "\nPlease Enter Maximum limit Value to print Odd Numbers =  ";
	cin >> maximum;
	
	cout << "\nList of Odd Numbers from " << minimumOdd << " to " << maximum << " are\n"; 
	for(int i = minimumOdd; i <= maximum; i++)
  	{
  		if ( i % 2 != 0 )
  		{
  			cout << i <<" ";
		}	
  	}
		
 	return 0;
}
C++ Program to Print Odd Numbers

此 C++ 打印奇数程序中的第一个 if 语句检查最小值是否能被 2 整除。如果为真,则它是一个偶数,因此将最小值增加 1;否则,进入 for 循环。

#include<iostream>
using namespace std;

int main()
{
	int minimumOdd, maximum;
	
	cout << "\nPlease Enter Minimum limit Value to print Odd Numbers =  ";
	cin >> minimumOdd;
	
	cout << "\nPlease Enter Maximum limit Value to print Odd Numbers =  ";
	cin >> maximum;
	
	if (minimumOdd % 2 == 0 ) 
    {
    	minimumOdd++;
    }
    
	cout << "\nList of Odd Numbers from " << minimumOdd << " to " << maximum << " are\n"; 
	for(int i = minimumOdd; i <= maximum; i = i + 2)
  	{
  		cout << i <<" ";
  	}
		
 	return 0;
}
Please Enter Minimum limit Value to print Odd Numbers =  50

Please Enter Maximum limit Value to print Odd Numbers =  80

List of Odd Numbers from 51 to 80 are
51 53 55 57 59 61 63 65 67 69 71 73 75 77 79