计算数字,直到获得所需的位数

时间:2016-10-21 20:42:58

标签: c digits

我是编码的新手。我现在正在学习C编程。我在计算数字方面遇到了问题。我的目标是只接受输入中固定数量的数字。例如,我希望用户只输入7位数字,所以当他们输入7位数字以外的任何东西时,程序应该让他们再次输入,直到它得到7位数字。这是我的尝试:

int n, count = 0;
printf("Please enter number:");
scanf("%d", &n);
printf("\n");

while (n != 0)
{
    n /= 10;
    count++;
}

printf("%d", count);
if (count != 7)
{
    printf("You can use only 7 digits numbers");
}

2 个答案:

答案 0 :(得分:0)

您可以通过创建一个小功能来检查为您输入的数字中的位数:

#include <stdio.h>

int count_digit(int n){
    int count = 0;

    if(n == 0) return 1;

    while(n != 0)
    {

        n /= 10;
        ++count;
    }
    return count;
}
int main(void) {
    int num;
    printf("Please enter number:");
    scanf("%d", &num);


    while (count_digit(num) != 7){
        printf("Please enter only 7digits number:\n ");
        scanf("%d", &num);
    }

    printf("The 7digit number you entered  is: %d",num);


    return 0;
}

答案 1 :(得分:0)

你可以尝试这个:

<system.web>
    <globalization culture="es-MX" uiCulture="es" />
</system.web>

获取输入后,如果需要,可以轻松将其转换为int。