繁体   English   中英

查找整数中出现的数字

[英]find digits occurence in an integer

伙计们,我无法创建一个函数来计算整数中数字的出现。 我创建2个int,int n包含从0到9的值。其中,int值是可以是1位数到9位数的数字。 我必须创建一个函数countOccurence来计算我输入的值中每个数字出现多少次。例如,如果我键入“ 12345”,则1 2 3 4 5出现一次,而6 7 8 9 0出现零。次。 我尝试过,但是我被卡住了。

这是我到目前为止提出的内容,我只是无法弄清楚。

#include <iostream>
using namespace std;

int main()
{
    int countOccurance(int, int);
    int findDig(int);

    int value;
    int n = 0;

    cout << "Please enter a positive number: " << endl;
    cin >> value;
    cout << "The value is " << value << endl;

    while ((value < 0) || (value > 999999999))
    {
        cout << "Invalid value. Please try again!" << endl;
        cout << "Please enter a positive number: " << endl;
    }

    //process the value

}

int countOccurance(int findDig, int value)
{

}

谢谢您的帮助,我非常感谢

这些思路可以为您提供所需的东西。

int findDig(int n) 
{
    if (n < 10)
        return 1;
    else 
       return 1 + findDig(n / 10);
}

int countOccurance(int value)
{
    for(int i = 0 ; i < 10 ; i++)
    {
        int val = value;
        int count = 0;
        while(val > 0)
        {
            if(val % 10 == i)
                count ++;
            val /= 10;
        }
        cout << count << " occourences of " << i << endl;
    }
}

int main()
{
    int value;
    int n = 0;

    cout << "Please enter a positive number: " << endl;
    cin >> value;
    cout << "The value is " << value << endl;

    while ((value < 0) || (value > 999999999))
    {
        cout << "Invalid value. Please try again!" << endl;
        cout << "Please enter a positive number: " << endl;
        cin >> value //you need this here, otherwise you're going to be stuck in an infinite loop after the first invalid entry
    }

    //process the value

    cout << endl;
    cout << "This " << value << " number is a " << findDig(value) << " digit integer number." << endl;

    cout << "Digit counts" << endl;

    countOccourance(value);
}

编辑

如果您需要countOccourence返回一个值,则应该这样做。

int countOccourence(int dig, int val)
{
    if(n > 0)
    {
        return countOccourence(dig, val / 10) + (val % 10 == dig);
    }
    else
        return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM