下面给出的代码可以使用(int
数据类型)精确到10位数,但对于超过10位的数字,它失败了,所以我尝试了unsigned long long int
。但现在我的输出固定为15,idk为什么?考虑我对C非常新,但我有平庸的python背景!
我正在使用gcc(Ubuntu 5.4.0-6ubuntu1~16.04.1)5.4.0 20160609
#include <stdio.h> //Get number of digits in a int
unsigned long long int get_len();
void main() {
unsigned long long int num;
printf("Enter the number:");
scanf("%d",&num);
printf("\nThe length of number is is: %d \n",get_len(num));
}
unsigned long long int get_len(unsigned long long int z) {
unsigned long long int i = 1;
while (1) {
if ((z/10) > 1) {
//printf("Still greater than 1");
i++;
z = z/10;
continue;}
else {
return(i+1);
break;}}}
您使用了错误的格式说明符。这将是scanf("%llu",&num);
在scanf
中使用错误的格式说明符是未定义的行为。
除了提到的内容之外,你的长度查找逻辑是错误的,因为单数字数字和多数字数字都会失败。
对于1
,它将返回2
的位数,对于其他数字也是如此。 (就像12
一样,它将返回3
)。
对于较大的数字,您可以选择选择库(大数字处理)或根据需要编写其中一个。
我会扫描像if( scanf("%llu",&num) != 1) { /* error */}
这样的数字。更清楚地检查scanf
的返回值。
这是另一个实现。这解决了一些问题:
int
。unsigned int
绰绰有余get_len()
返回类型。unsigned int
和unsigned
是一样的。 unsigned long long int
也可以被剥夺int
。#include <stdio.h> unsigned get_len(); int main() { unsigned long long num; printf("Enter the number: "); scanf("%llu", &num); printf("\nThe length of number is: %u\n", get_len(num)); } unsigned get_len(unsigned long long z) { return (z / 10 > 0) ? get_len(z / 10) + 1 : 1; }