gpt4 book ai didi

c++ - 如何计算 “numbers in for”的数量

转载 作者:行者123 更新时间:2023-12-02 09:53:50 32 4
gpt4 key购买 nike

大家,我建立了一个程序,可以从给定的数字中知道偶数和奇数。

偶数和奇数工作得很好,我想知道从开始到结束的数字总数,但是对于两者,输出总说11。
我该如何解决?并且有任何计数字母/数字的功能,因为它将非常有帮助。
我确实搜索过,但是找不到任何谢谢

#include<stdio.h>
#include <iostream>
using namespace std;


int main(){

int number;
int firstNum,secondNum;
int countOdd,countEven;

cout << "Enter the first number: ";
cin >> firstNum;

cout << "Enter the second number: ";
cin >> secondNum;

if (firstNum>secondNum )
cout << "Sorry the first number must be less than second number";

else

cout << "Odd numbers in given range are: ";
for(number = firstNum;number <= secondNum; number++)

if(number % 2 !=0)
cout << number<< " ";
countOdd = number;
cout << "\nTotal count of odd number is :" << countOdd << endl;

printf("\nEven numbers in given range are: ");
for(number = firstNum;number <= secondNum; number++)

if(number % 2 ==0)
cout << number << " ";
countEven = number;
cout << "\nTotal count of even number is :" << countEven << endl;

return 0;
}

最佳答案

计算奇数和偶数的代码:

using namespace std; 

// Return the number of odd numbers
// in the range [L, R]
int countOdd(int L, int R){

int N = (R - L) / 2;

// if either R or L is odd
if (R % 2 != 0 || L % 2 != 0)
N += 1;

return N;
}

// Driver code
int main()
{
int L = 3, R = 7;
int odds = countOdd(L, R);
int evens = (R - L + 1) - odds;

cout << "Count of odd numbers is " << odds << endl;
cout << "Count of even numbers is " << evens << endl;
return 0;
}

关于c++ - 如何计算 “numbers in for”的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62056927/

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