从下列程序中求除数的奇数

finding the odd numbers from below programs divisors

本文关键字:程序      更新时间:2023-10-16
 #include <iostream>
using namespace std;
int main()
{    int i,num1,num2,sum=0,count=0;
     cout<<"Enter a range: ";
     cin>> num1>> num2;
     for(i = num1;i <= num2; i++)
     if(i%3 ==0 ||i%5 ==0)
    {
        count++;
       //sum=sum+i;
       cout<<i<<" ";
    }
     return 0;
}

我编写了一个程序来查找给定范围内3和5的除数,但是现在我想从这些除数中找到奇数。怎么做?假设我在这个程序中输入1到20的范围。我将得到除数:3 5 6 10 12 15 18 20。现在我想从这些数中得到奇数。怎么做?

如果要检查i是否为奇数,只需将i % 2!= 0添加到条件中。正如leaf指出的那样,不要使用using namespace std;,当你在那里时,为什么不实际使用变量count呢?

#include <iostream>
int main(){
    int low{ 0 };
    int max{ 0 };
    std::cout << "Type in low: ";
    std::cin >> low;
    std::cout << "Type in max: ";
    std::cin >> max;
    unsigned int count{ 0u };
    for (int i = low; i < max; ++i){
        if (i % 2 != 0 && (i % 3 == 0 || i % 5 == 0)){
            ++count;
            std::cout << i << " ";
        }
    }
    std::cout << "nNumber of odd integers that are multiples of 3 or 5 found: " << count << std::endl;
    return 0;
}

示例运行:

Type in low: 300
Type in max: 795
303 305 309 315 321 325 327 333 335 339 345 351 355 357 363 365 369 375 381 385
387 393 395 399 405 411 415 417 423 425 429 435 441 445 447 453 455 459 465 471
475 477 483 485 489 495 501 505 507 513 515 519 525 531 535 537 543 545 549 555
561 565 567 573 575 579 585 591 595 597 603 605 609 615 621 625 627 633 635 639
645 651 655 657 663 665 669 675 681 685 687 693 695 699 705 711 715 717 723 725
729 735 741 745 747 753 755 759 765 771 775 777 783 785 789
Number of odd integers that are multiples of 3 or 5 found: 115