Need help with function.

Hello,
I wrote a program, witch finds how many digits 2 appear in the number and then multiplies them. But I don't know how to write a function for this.
Could anyone please help me?
Thanks.
P.S Sorry for my bad english.
#include <iostream>
using namespace std;
int main()
{
	int a, b;	
	int san1, san2;
	int x, y;
	cout << "Type you number. First A:	"<<endl;
	cin >> a;
	san1 = 1;
	san2 = 1;
	while (a>0)
	{	x = a%10;
		a = a/10;					

			if (x==2)
			san1 = san1 * x;
	}
	cout << "Type your second number B:	"<<endl;
	cin >> b;
	while (b>0)
	{	y = b%10;
		b = b/10;

			if (y==2)
			san2 = san2 * y;
	}
	if (san1==1)
		san1 = 0;
	if (san2==1)
		san2 = 0;
	cout <<"Number A product of 2 is: "<<san1<<endl;
	cout <<"Number B product of 2: "<<san2<<endl;
	if (san1>san2)
		cout <<"B has lower product of digits 2 than A"<<endl;
	else if (san2>san1)
		cout <<"A has lower product of digits 2 than B"<<endl;
	if (san1=san2)
		cout <<"Both has same amount."<<endl;
	return 0;
	}
Help anyone please?
I'm not sure what you are trying to do here.

You want to write a function that receives a number and returns a number of numbers in an integer?

Or do you want to take the code you posted above and put it all in a function?
Something like this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
using std::cin; using std::cout; using std::endl;

int pwrOfTwos(int num)
{
    int output = 1;
    while (num > 0)
    {
        if (num%10 == 2) // is the least-significant place a 2?
            output *= 2; // If so, multiply by 2!
        num /= 10;       // Shift by 1 decimal place
    }

    if (output < 2) return 0; // No twos
    return output;
}

int main()
{
    int a, b;    
    cout << "Type you number. First A: "<<endl;
    cin >> a;
    cout << "Type your second number B: "<<endl;
    cin >> b;

    a = pwrOfTwos(a);
    b = pwrOfTwos(b);

    cout <<"Number A product of 2 is: " << a <<endl;
    cout <<"Number B product of 2 is: " << b <<endl;

    if      (a>b) cout <<"B has lower product of digits 2 than A"<<endl;
    else if (b>a) cout <<"A has lower product of digits 2 than B"<<endl;
    else          cout <<"Both has same amount."<<endl;

    return 0;
}


It checks how many 2's are in a decimal number and then outputs the product of the twos.
Last edited on
Topic archived. No new replies allowed.