找到奇数乘积和偶数量的程序

时间:2013-11-01 20:30:39

标签: c++

//task: to write a program which in the interval from n to m would find 
//odd numbers product and even numbers amount.

#include <iostream>

using namespace std;

int main()
{
int n, m; //numbers
int k; //loop's variable
int r; //product
int s=0; //sum
cout<<"Write two numbers - "<<endl;
cout<<"The first number: "<<endl;
cin>>n;
cout<<"The second number: "<<endl;
cin>>m;
if (n>m)
swap(n,m);
r=1;
for (k=n; k<=m; k+=1)
    {
        if (k%2==0) //even
        s+=k;

        else // odd
        r*=k;
    }

cout <<"s = "<<s<<endl;
cout<<"r = "<<r<<endl;

}


return 0;
}

此代码现在有效!

任务是:假设n = 1,m = 10偶数将是2,4,6,8,10,其数量将是= 30。奇数将是1,3,5,7,9,其产品将是= 945.所以我需要在屏幕上显示数量(30)和产品(945)。

2 个答案:

答案 0 :(得分:1)

循环遍历所有数字(从n-> m),确定每个数字是偶数还是奇数,求和均数,乘以几率:

    for (k=n; k<=m; k+=1)
    {
        if (n%2==0) //even
            s+=k;
        else // odd
            r*=k;
    }

    cout <<"s"<<s<<endl;
    cout<<"r"<<r<<endl;

以下是我将如何完成整个计划:

#include <iostream>

using namespace std;

int main()
{
    int firstNumber, secondNumber; //numbers
    cout << "Write two numbers - " << endl;
    cout << "The first number: " << endl;
    cin >> firstNumber;
    cout << "The second number: " << endl;
    cin >> secondNumber;

    if (firstNumber > secondNumber)
    {
        swap(firstNumber, secondNumber);
    }

    int sum = 0;
    int product = 1;
    for (int i = firstNumber; i <= secondNumber; i++)
    {
        if (i % 2 == 0) //even
        {
            sum += i;
        }
        else // odd
        {
            product *= i;
        }
    }

    cout << "Sum: " << sum << endl;
    cout << "Product" << product << endl;

    return 0;
}

答案 1 :(得分:0)

int s; ===&gt; int s=0;

if (n%k==0) ===&gt; if (k%2==0)

<强>代码:

#include <iostream>

using namespace std;

int main()
{
int n, m; //numbers
int k; //loop's variable
int r; //product
int s=0; //sum
cout<<"Write two numbers - "<<endl;
cout<<"The first number: "<<endl;
cin>>n;
cout<<"The second number: "<<endl;
cin>>m;
if (n>m)
swap(n,m);
r=1;


    for (k=n; k<=m; k+=1)
    {
        if (k%2==0) //even
           s+=k;
        else // odd
           r*=k;
    }

    cout <<"s"<<s<<endl;
    cout<<"r"<<r<<endl;