简体   繁体   English

如何在C中的4位数字的每个数字加2

[英]How to add 2 to each digit in a 4 digit number in C

I am trying to solve this tutorial practice question that doesn't have an answer that I can check my code against. 我正在尝试解决本教程练习中的问题,该问题没有可以检查我的代码的答案。 The goal is to write a program to display numbers whose digits are 2 greater than the corresponding digits of the entered number. 目标是写一个程序来显示其数字是数字2比输入的号码的对应位数越大。 So if the number input is 5656 then the output number should be 7878 . 因此,如果输入的数字是5656则输出的数字应该是7878 I have figured out how to separate each number and add them, but I can't seem to get them to print in a four-digit sequence. 我已经弄清楚了如何分隔每个数字并将它们相加,但是我似乎无法让它们以四位数的顺序打印。


#include <stdio.h>

int main ()
{
    int n, one, two, three, four, final;
    scanf("%d", &n);

    one   = (n / 1000);
    n     = (n % 1000) + 2;
    two   = (n / 100) + 2;
    n     = (n % 100) + 2;
    three = (n / 10) + 2;
    n     = (n % 10) + 2;
    four  = (n / 1) + 2;
    n     = (n % 1) + 2;

    final = (one * 1000) + (two * 100) + (three * 10) + four;

    printf("%d", final);
    return 0;
}
#include <stdio.h>
int main()
{
     int n,a[4], final;
    scanf("%d", &n);
    for(int i=3;i>=0;i--)
    {
        a[i]=n%10+2;
        n/=10;
    }
    final = (a[0] * 1000) + (a[1] * 100) + (a[2] * 10) + a[3];
    printf("%d", final);
    return 0;
}

Below function works with N number of digits. 以下功能适用于N个数字。 Idea is to extract each digit from the input number and add its decimal position. 想法是从输入数字中提取每个数字并添加其小数位。

#include <stdio.h>

int power(int x, int y)
{
  int res = 1;
  for (;y>0;y--)
  {
    res *=x;
  }
  return res;
}
int main ()
{
    int n;
    scanf("%d", &n);
    int sum = 0;
    int i=0;
    while(n>0)
    {
       sum += ((n%10) +2)*power(10,i);
       i++;
       n /=10;
    }

    printf("%d", sum);
    return 0;

}

Another idea: 另一个想法:

char str[10]; // enough to contain an int as string + 1
char *s = str+sizeof(str); // points to last char + 1
int n;

scanf("%d", &n);
*--s = 0;  // terminate the string

while(n) {
    *--s = (((n % 10)+2)%10) + '0'; // write a char from the end
    n /= 10;
}
printf("%s\n", s);

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

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