gpt4 book ai didi

c - 如何计算数字中的位数,包括前导零?

转载 作者:行者123 更新时间:2023-11-30 20:50:37 37 4
gpt4 key购买 nike

此代码尝试计算输入数字中的数字。

如果输入数字是06584,则该代码的输出将为4,不包括零。如何获得 5 作为输出(因此计算零)?

#include<stdio.h>
void main()
{
int n,c=0,d;
printf("Enter no\n");
scanf("%d",&n);
while(n!=0)
{
d=n%10;
c++;
n=n/10;
}
printf("No of digits=>%d\n",c);
}

最佳答案

How to count the digits in a number, including leading zeros?

要计算输入的位数(包括前导 0 位数),请记录数字前后的扫描偏移量。此方法将符号字符报告为数字,但不计算前导空格。

使用"%n"记录到目前为止扫描的字符数。 @BLUEPIXY

#include<stdio.h>

int main() {
int begin;
int after = 0;
int number;
printf("Enter number\n");
fflush(stdout);
// +--- consumes leading white-space
// | +- record number of characters scanned
scanf(" %n%d%n", &begin, &number, &after);
if (after > 0) {
printf("No of digits: %d\n", after - begin);
printf("Value read : %d\n", number);
} else {
puts("Invalid input");
}
}

输出

Enter number
000123
No of digits: 6
Value read : 123

关于c - 如何计算数字中的位数,包括前导零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42542814/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com