c - 如何存储我试图分隔的整数的数字?

标签 c algorithm

我遇到的问题是,我想获取一个整数并将其分开。例如:用户输入:23432。控制台应该打印“2 3 4 3 2。我遇到的问题是存储该数字。例如,

  User Input : 2020
  assign input to num.
  digit = 2020 % 10 = 0 <--- 1st Digit
  num = num / 10 = 202
  digit2 = num % 10 = 2 <--- 2nd Digit
  num = num / 100 = 20.2 
  temp = round(num) = 20
  digit3 = num % 10 = 0 <--- 3rd Digit
  digit4 = num / 10 = 2 <---- 4th Digit

这种方法的问题在于它依赖于用户输入,我正在使用范围 1-32767,所以我不知道要创建多少个数字变量。使用我创建的结构,有人可以帮助让它以某种方式运行,无论数字是什么,数字都会按照我描述的方式保存和打印?

int Rem(int num);
  int Div(int num);

  int main() {
      int num;
      printf("Enter an integer between 1 and 32767: ");
      scanf("%d", &num);
      Rem(num);
      Div(num);
      printf("%d","The digits in the number are: ");

  }


      int Rem(int num) {
          int rem = num % 10;
          return rem;
      }

      int Div(int num){
          int div = num / 10;
          return div;
      }

最佳答案

The problem with this approach is that its dependent on the user input, I'm working with the range 1-32767, so I wont know how many digit variables to create.

所以计算一下。您可以通过每次将变量增加 10 倍来实现此目的,直到再增加一次将使其大于您的输入数字:

int num;
printf("Enter an integer between 1 and 32767: ");
scanf("%d", &num);
int div = 1;
while(div * 10 <= num)
    div *= 10;

然后,您可以重复将您的数字除以该除数以获得每位数字,每次将除数除以 10 一次移动一位:

printf("The digits in the number are: ");
while(div > 0)
{
    printf("%d ", (num / div) % 10);
    div /= 10;
}

关于c - 如何存储我试图分隔的整数的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56606150/

相关文章:

c - 如何在没有相邻空行的情况下打印标准输入或文件的内容?

C++行进立方体算法解释

algorithm - 为什么贪心算法对某些不同于美国货币的货币不起作用?

algorithm - 如何根据操作数计算时间复杂度

c - 为什么这些构造使用增量前和增量后未定义的行为?

Android NDK wifi 示例

c - 为什么不对 MEMORY 类的类型执行尾调用优化?

javascript - "reduce"嵌套数组到带键对象的最快方法+按键查找的最快方法

python - 一种确定两个句子相似程度的算法

c - C中for循环被抽象为Macro时的无限循环