从下面的程序除数中找出奇数

时间:2016-11-17 19:29:28

标签: c++ modular

 #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。现在我想从这个数字得到奇数。怎么做? ?

1 个答案:

答案 0 :(得分:0)

如果您想检查i是否为奇数,只需将i % 2!= 0添加到条件中即可。 另外正如叶子指出的那样,不要使用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