【问题标题】:C: Character input with scanfC: 用 scanf 输入字符
【发布时间】:2017-06-05 18:36:34
【问题描述】:

我有一个简单的程序,可以将浮点数 x 提高到整数 n 的幂。我添加了一个 while 循环来重复提供适当输入的过程(此处“Y”为“是”)。但是,当我在 scanf(" %c",anwser); 键入任何字符时程序失败并关闭。有什么想法吗?

float x;
 char *anwser='Y';
 int n,k;
 while (anwser=='Y'){
   printf("Give floating point number x to be raised at the power of n \n ");
   scanf("%f%d",&x,&n);
   printf(" \n result : %f",power(x,n));
   printf("\nDo again?? ");
   scanf(" %c",anwser);
  }

float power(float x , int n){
     int i;
     float pow=1;
     for(i=0;i<n;i++) pow*=x;
     return pow;
}

【问题讨论】:

  • 'Y' 是一个字面常量,这意味着你不能写入它。您尝试在 scanf 中执行此操作。而是使用可写字符并将其初始化为“Y”。
  • 旁白:除非您的环境停留在 20 世纪,否则请始终使用 double。不幸的是,教科书的遗产太老了,早于double

标签: c character scanf


【解决方案1】:

您不需要char* 来存储像'Y' 这样的字符。 这是您的工作代码,带有一些小模块:

 #include <stdio.h>

 int main(void)
 {
     double base;
     size_t exp;
     double res = 1;
     char answer;
     do {
         printf("Give floating point number x to be raised at the power of n: \n");
         scanf(" %lf%zu", &base, &exp);
         for (size_t i = 0; i < exp; i++) {
             res *= base;
         }
         printf("Result: %lf\n", res);
         printf("Do you want repeat? (y/Y or n/N)\n");
         scanf(" %c", &answer);
         res = 1;
     }while (answer == 'Y' || answer == 'y');
     return 0;
 }

【讨论】:

  • 很酷,但是在“为什么”方面做一点解释会更好,恕我直言。
猜你喜欢
  • 2021-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-22
  • 2021-07-31
  • 1970-01-01
  • 2019-10-24
相关资源
最近更新 更多