检查用户输入长度(C编程)

时间:2018-02-23 15:41:21

标签: c input user-input palindrome

我正在研究一个相当简单的问题,但我遇到了一个问题,并且不确定为什么程序没有按照我想要的方式工作。问题要求我们使用功能进行Palindrome测试。我能够做到这一切,但在问题中它还要求我们确保用户输入是一个5位数字。这就是我在代码中所做的:

 do {
   printf("Please Enter a positive 5-digit number: "); //Ask & receive input
   scanf("%d", &number);
   countdigs = countDigits(number); //
   }while((countdigs != 5) && (number <0) );//keep going throught the loop while the number is less than 0 and is not equal to 5 digits    
 palindrome(number); //palindrome

这是我的回文功能

void palindrome (int number) //create palindrome procedure
{ 
 int remainder,reversedNumber=0,original; //initialize variables
 original = number; //set original number to a new var
 while (number != 0) //while the number is not 0
 {
  remainder = number %10; //get remainder of original number
  reversedNumber = (reversedNumber*10) + remainder; //construct reversed 
  number
  number = number / 10; //go to the next digit
 }
 //printf("OG = %d",original); //check
 //printf("rev = %d", reversedNumber); //check
 if (original == reversedNumber) //if the original number and reversed 
 number are the same
 {
  printf("The number %d is a palindrome.\n",original);  //print solution
 }
 else //if not the same
 {
  printf("The number %d is not a palindrome.\n",original); //print solution
 }
}

这是我的countDigits函数

int countDigits(int number) //setup recursive function
{
 int number_length=0; //initialize number length
 while(number != 0) //while the number is not 0
 {
  number = number/10; //divide number by 10 to get to next digit
  number_length = number_length + 1; //increase counter by 1
 }  
 return number_length; //return the counter
 printf("length %d",number_length);  
}

我遇到的问题是在此代码中(countdigs!= 5),这是检查以确保数字是正数(正常工作),并确保数字长度但是,我无法让它发挥作用。

问题说不使用任何字符串函数(长度函数)

1 个答案:

答案 0 :(得分:3)

我想这个问题刚刚开始:

do {
    printf("Please Enter a positive 5-digit number: ");
    scanf("%d", &number);
    countdigs = countDigits(number);
} while((countdigs != 5) && (number < 0) );

如果countdigs != 5number为否定,我们应该再次要求用户输入,即:

do {
    printf("Please Enter a positive 5-digit number: ");
    scanf("%d", &number);
    countdigs = countDigits(number);
} while((countdigs != 5) || (number < 0) );