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;
}
#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;
elseif (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.