【问题标题】:Counting digits in a number without using strings在不使用字符串的情况下计算数字中的数字
【发布时间】:2014-04-23 11:12:09
【问题描述】:

我有下一个代码,它要求用户输入一个非常长的数字,例如 100000000,然后它会打印给定数字出现在该数字上的次数,代码工作正常并且一切正常,但教授告诉我我不必使用字符串或字符,但是当代码向用户询问数字时,它必然需要一个字符串,而我不知道如何修改它,我使用了 gmp 库

#include <iostream>
#include <stdio.h>
#include <gmp.h>
#define MAX 40

using namespace std;

void searchDigit(FILE *fd);
int NewNumber();

int main()
{
    FILE *fd;
    int otherNumber;
    string text;
    mpz_t num;
    do
    {
        if((fd = fopen("File.txt","w+"))!= NULL)
        {
            mpz_init(num);
            cout << "Give me the number: " << endl;
            cin >> text;
            mpz_set_str(num,text.c_str(),10);
            mpz_out_str(fd,10,num);
            fclose(fd);
            searchDigit(fd);
            otherNumber = NewNumber();
        }
        else
           cout << "Fail!!" << endl;
    }while(otherNumber);
    return 0;
}

void searchDigit(FILE *fd)
{
    int car,continue = 1,r;
    char answer,digit;
    if((fd = fopen("File.txt","r"))!= NULL)
    {
        do
        {
            r = 0;
            fseek(fd,0,SEEK_SET);
            cout << "What digit do you want to search? " << endl;
            cin >> digit;
            while((car = fgetc(fd))!= EOF)
            {
                if(car == digit)
                   r++;
            }
            cout << "The digit x=" <<digit<< " appears " << r << " times" << endl;
            cout << "Do you want to search any other digit? " << endl;
            cin >> answer;
            if(answer != 'S')
               continue = 0;
        }while(continue);
    }
    else
       cout << "Fail!!" << endl;
}

int NewNumber()
{
    char answer;
    cout << "DO you wish to work with a new number? " << endl;
    cin >> answer;
    if(answer == 'S' || answer == 's')
       return 1;
    else
       return 0;
}

提前致谢

【问题讨论】:

  • 可以进行位运算。
  • continue 是 C++ 关键字。那是怎么编译的??
  • 感谢您的回答,@adifire 您对按位运算是什么意思?,我如何在我的代码中使用它们

标签: c++ string parsing numbers digits


【解决方案1】:

取决于您的输入实际上可能有多大...但是对于检索数字,您可以执行以下操作:

#include <iostream>
using namespace std;

typedef unsigned long long UINT64;

int main() {
    UINT64 i;
    std::cin >> i;
    while (i >= 1) {
        int digit = i % 10;
        std::cout << digit << " ";
        i /= 10;
    }
}

输入:18446744073709551614

输出:4 1 6 1 5 5 9 0 7 3 7 0 4 4 7 6 4 4 8 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-18
    相关资源
    最近更新 更多