给定一个从L到R的整数范围,任务是计算该范围内的奇数和偶数。
输入-L = 7,R = 17
输出-L到R范围内的偶数计数为-5
从L到R范围内的奇数计数为-6
输入-L = 1,R = 10
输出-L到R范围内的偶数计数为-5
从L到R范围内的奇数计数为-5
输入从L到R的范围
将L和R值传递给函数以找出偶数,然后我们将根据返回值计算奇数。
从i到L到R开始循环
在循环内部,检查IF i%2 == 0,然后将偶数加1
返回偶数
现在要计算将奇数设置为(R-L + 1)-偶数的奇数
#include <iostream> using namespace std; int Odd_Even(int L, int R){ int even = 0; for(int i = L ;i < R ;i++){ if(i%2==0){ even++; } } return even; } int main(){ int L = 7, R = 17; int even = Odd_Even(L, R); int odd = (R - L + 1) - even; cout<<"Count of Even numbers in a range from L to R are: "<<even<<endl; cout<<"Count of Odd numbers in a range from L to R are: "<<odd; return 0; }
输出结果
如果我们运行上面的代码,它将生成以下输出-
Count of Even numbers in a range from L to R are: 5 Count of Odd numbers in a range from L to R are: 6