【问题标题】:In this program to determine whether number is palindrome or not, I can't figure out what's going wrong? I think scanf isn't even taking value在这个确定数字是否回文的程序中,我不知道出了什么问题?我认为 scanf 甚至没有价值
【发布时间】:2021-03-07 18:37:18
【问题描述】:

我试图在不使用库函数和数组的情况下检测一个数字是否为回文。我不认为逻辑是这里的问题。我在扫描和一些循环之后引入了 printf 作为检查点,但我认为代码甚至没有读取输入,因为它无法打印输入的值

#include<stdio.h>
int main()
 {
     long a,b,x,i,j,d,y;
     long g=0;
     long n=0;
     long c=10;
  printf("Enter a number: "); 
  scanf("%li",&a);   \\takes input
  printf("%li",a);   \\prints the scanned input(Checkpoint)
  do{
     n++;
     b=a/10;
    }while(b!=0);  \\to determine the number of digits in input
    printf("%li",n);  \\(checkpoint)
  x=a;
  for(i=0;i<n;i++) 
   y=c*10;
printf("%li",y);  \\(checkpoint)
  for(j=0;j<n;j++)  \\store the reverse value of input in g
  {
   d=x%c;
   y=y/10;
   g=g+(d*y);
   x=x/10;
  }
  if(g==a)  \\check if number is palindrome
  {
   printf("Palindrome");
  }
  else
  {
   printf("Not a palindrome");
  }
  return(0);
 }

【问题讨论】:

  • 始终检查 scanf returns 的内容。
  • 嗨,欢迎来到 SO!你的“评论标记”是错误的:它应该是//,而不是`\\`。
  • 请不要在您的帖子中标记多种不同的语言,仅使用您实际编程语言的标签。
  • 由于您不打印任何换行符,因此您没有刷新输出缓冲区,因此您看不到检查点,因此您不会注意到您的第一个循环永远不会结束。 (如果a/10a 始终不变,b 怎么会变为零?)

标签: c fatal-error


【解决方案1】:

在循环中

do{
     n++;
     b=a/10;
    }while(b!=0);

您永远不会修改a 的值,因此a/10 的结果以及b 的值将始终相同。如果a 等于或大于10,那么这里就会出现无限循环,因为b 永远不会等于0。

由于循环之前的输出没有刷新(实际上是写入终端),所以看起来scanf 调用将永远不会返回。

【讨论】:

    猜你喜欢
    • 2021-01-25
    • 2022-01-14
    • 1970-01-01
    • 2021-09-04
    • 2020-08-17
    • 2023-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多