加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

为什么这个C程序将T 1输入改为T?

发布时间:2020-12-16 10:40:41 所属栏目:百科 来源:网络整理
导读:#include stdio.hint main (void) { int T,y,z; scanf ("%in",T); for (T; T 0 ; --T) { scanf ("%in",y); }return 0;} 如果输入4,是否应该再输入4个?相反,它允许我输入5个整数!也尝试过其他数字. 解决方法 scanf中的格式字符串的工作原理如下(见 http:/
#include <stdio.h>
int main (void) 
{
  int T,y,z;
  scanf ("%in",&T);
  for (T; T > 0 ; --T) 
  {
   scanf ("%in",&y);
  }
return 0;
}

如果输入4,是否应该再输入4个?相反,它允许我输入5个整数!也尝试过其他数字.

解决方法

scanf中的格式字符串的工作原理如下(见 http://www.cplusplus.com/reference/cstdio/scanf/)

[The format is a] C string that contains a sequence of characters that control how
characters extracted from the stream are treated:

Whitespace
character
: the function will read and ignore any whitespace characters
encountered before the next non-whitespace character

在你的scanf()中都有换行符.因此,第一次按Enter键时,scanf会忽略它.

一些答案告诉你修改循环……这是不正确的,你的循环没问题.以上就是让你头痛的问题.请尝试以下方法:

#include <stdio.h>
int main(int argc,char const *argv[])
{
  int T,z;
  scanf ("%i",&T);

  printf("Count is= %dn",T);
  for (T; T > 0 ; --T) 
  {
      printf("T= %dn",T);
      scanf ("%i",&y);
  }
return 0;
}

编辑:感谢Daniel Fischer关于冲洗stdin的评论,我现在已将其删除.找到了这个解释(Using fflush(stdin)).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读