【问题标题】:Finding a number at a particular digit in a number [closed]在数字中的特定数字处查找数字[关闭]
【发布时间】:2015-10-15 07:05:12
【问题描述】:

我想获取特定索引处的数字。

假设号码是“123456789”,我需要返回左起第 3 位的号码。

我应该将此数字转换为字符串并将特定索引处的字符重新转换为整数以获得数字值吗?

在 C++ 中是否有任何内置函数可以这样做?

【问题讨论】:

  • 数字是整数还是字符串?这个问题很模糊。
  • 整数@VioletGiraffe
  • 我投票结束这个问题,因为学生没有表现出任何努力来解决他的家庭作业。
  • 最简单的方法可能是将其转换为字符串。

标签: c++ c++11 numbers integer digits


【解决方案1】:

要获取数字中任何位置的数字,可以使用简单的字符串转换:

int foo = 123456789;
int pos = 3;
// convert to string and use the [] operator
std::cout << std::to_string(foo)[pos - 1];//need to subtract 1 as C++ is 0 index based

【讨论】:

    【解决方案2】:

    这应该返回一个数字的第三个数字!

    cout << "Enter an integer";
    int number;
    cin >> number;
    int n = number / 100 % 10
    

    或(对于所有数字):

     int number = 12345;
     int numSize = 5;
    for (int i=numSize-1; i>=0; i--) {
      int y = pow(10, i);
      int z = number/y;
      int x2 = number / (y * 10);
      printf("%d-",z - x2*10 );
    }
    

    【讨论】:

    • 但是 OP 指定他想要 left 的第三个数字,而不是 right 的第三个数字。
    • @VioletGiraffe 12345/1000=12
    • 这个答案的总体思路可能仍然与counting the digits 一起工作(计算numSize)。
    【解决方案3】:

    std::stringstream的使用

    std::string showMSD3(int foo)
    {
       std::stringstream ssOut;
    
       std::string sign;
       std::stringstream ss1;
       if(foo < 0) {
          ss1 << (-1 * foo);
          sign = '-';
       }
       else
          ss1 << foo;
    
       std::string s = ss1.str();
    
       ssOut << "               foo string: '"
             << sign << s << "'" << std::endl;
    
       if(s.size() > 2)
       {
          ssOut << " Most Significant Digit 3: "
                << s[2] // 1st digit at offsset 0
                << "\n            has hex value: 0x"
                << std::setw(2) << std::setfill('0') << std::hex
                << (s[2] - '0')
                << std::endl;
       }
       else
          ssOut << "                      Err: foo has only "
                << s.size() << " digits" << std::endl;
    
       return (ssOut.str());
    }
    

    并且在更接近 main 的地方(可能在 main 中):

       // test 1
       {
          std::cout << showMSD3(123456789) << std::endl;
       }
    
       // test 2
       {
          std::cout << showMSD3(12) << std::endl;
       }
    
       // test 3 - handle negative integer
       {
          std::cout << showMSD3(-123) << std::endl;
       }
    

    有输出

                   foo string: '123456789'
     Most Significant Digit 3: 3
                has hex value: 0x03
    
                   foo string: '12'
                          Err: foo has only 2 digits
    
                   foo string: '-123'
     Most Significant Digit 3: 3
                has hex value: 0x03
    

    【讨论】:

      猜你喜欢
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 2014-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-02
      相关资源
      最近更新 更多