您收到一个号码。函数应通过将数字中的每个数字 (d=1,2,3,...) 更改为 d+1 来创建新数字。如果 9 位于数字中间,则会将其变为 0。您不应该检查特定数字是否为 9 (!) 。 该函数应返回一个新数字。
我的代码中的问题是,当我得到一个以 9 开头的数字时,它一开始会显示 0(但不应该如下面的示例所示)。
//if input 879021 - output 980132
//if input 930 - output 41
//if input 9999 - output 0
//working with visual studio 2017
void num_incr(int number);
void main(){
int number = 0;
printf("Enter a whole number: ");
scanf_s("%d", &number);
num_incr(number);
}
void num_incr(int number) {
if (number <= 0) {
return;
}
num_incr(number / 10);
printf("%d", (number % 10 + 1) % 10);
}
最佳答案
要去掉开头的 0,首先将返回函数设置为整数,最后打印。
另外,在当前代码中,递归尚未完成,因为正整数除以 0 后仍为正数。
//if input 879021 - output 980132
//if input 930 - output 41
//if input 9999 - output 0
//working with visual studio 2017
int num_incr(int number);
void main(){
int number = 0;
printf("Enter a whole number: ");
scanf_s("%d", &number);
printf("%d\n", num_incr(number));
}
int num_incr(int number) {
if (number <= 0) {
return 0;
}
int up_part = num_incr(number / 10);
return up_part * 10 + ((number % 10 + 1) % 10);
}
关于C语言,序列每个数加1。如何去掉开头的0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48084720/