You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

温度转换C程序故障:scanf函数跳过目标转换单位问询

问题原因

你遇到的scanf跳过输入的问题,根源是输入缓冲区残留的换行符。当你用scanf("%f", &a)读取完温度数值后,按下的回车键会被留在输入缓冲区里,后续的scanf("%c", &e)会直接读取这个换行符,而不是等待你输入目标单位,看起来就像是跳过了输入步骤。

解决办法

有两种简单的修复方式:

  • 在读取字符的scanf格式串前加空格,空格会自动忽略缓冲区里的空白字符(包括换行、空格、制表符):
    scanf(" %c", &e);  // 注意%c前面的空格
    
  • 读取完浮点数后,用getchar()清空缓冲区里的换行符:
    scanf("%f", &a);
    getchar();  // 吃掉残留的换行符
    
修复后的完整代码
#include <stdio.h>

int main()
{
  float a, b;
  char c, e;

  printf("What you want to change\ntype c for celcius, f for farenheit or k for kelvin: ");
  scanf("%c", &c);

  switch (c)
  {
  case 'c':
    printf("Now put the celcius value you want to convert: ");
    scanf("%f", &a);

    printf("Now in which you want to change\ntype f for farenheit or k for kelvin: ");
    scanf(" %c", &e);

    switch (e)
    {
    case 'f':
      printf("The farenheit value of %0.2f degree celcius: %0.2f\n", a, a*1.8+32);
      break;

    case 'k':
      printf("The kelvin value of %0.2f degree celcius: %0.2f\n", a, a+273.15);
      break;
       
    default:
      printf("You didnt put the correct operation");
      break;
       
    }
    break;

  case 'f':
    printf("Now put the farenheit value you want to change into celcius: ");
    scanf("%f", &a);
    b = ((a-32)*5)/9;

    printf("Now in which you want to change\ntype c for celcius or k for kelvin: ");
    scanf(" %c", &e);

    switch (e) {
  case 'c':
    printf("The celcius value of %0.2f degree farenheit: %.2f\n", a, b);
    break;

  case 'k':
    printf("The kelvin value of %0.2f degree farenheit: %0.2f\n", a, b+273.15);
    break;

  default:
    printf("You didnt put the correct operation");
    break;
        }
    break;


  case 'k':
    printf("Now put the kelvin value you want to change: ");
    scanf("%f", &a);

    if (a>=0) {
      printf("Now in which you want to change\ntype c for celcius or f for farenheit: ");
      scanf(" %c", &e);
      b=(a-273.15)*1.8+32;
      switch (e) {
  case 'c':
    printf("The celcius value of %0.2f kelvin in celcius is: %0.2f\n", a, a-273.15);
    break;

  case 'f':
    printf("The farenheit value of %0.2f kelvin in farenheit is: %0.2f\n", a, b);
    break;

  default:
    printf("You didnt put the correct operation");
    break;
                
      }}

    else {
      printf("Kelvin cannot be less than zero");
    }
    break;

  default:
    printf("You didnt put the correct spell of what you want to change\n");                
    break;
  }
  return 0;
}

内容的提问来源于stack exchange,提问作者anon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 04:55:42