【问题标题】:Using scanf() to obtain a single integer使用 scanf() 获取单个整数
【发布时间】:2015-01-26 18:15:19
【问题描述】:

我只是使用这个小程序来避免在纸上遍历三个骰子的所有可能组合。它使用 scanf() 接受输入,然后检查每个组合以查看骰子的总和是否是提供的数字。

#include <stdlib.h>
#include <stdio.h>

void main() {
    int a,b,c,s,num=0;
    printf("Enter the desired sum:");
    scanf("%d",&s);
    printf("Seeking for sums of %d",s);
    for(a=1; a++; a<=6) {
        for(b=1; b++; b<=6) {
            for(c=1; c++; c<=6) {
                if(a+b+c==s) {
                    num++;
                    printf("Die 1: %d, Die 2: %d, Die 3: %d",a,b,c);
                }
            }
        }
    }
}

问题是,程序没有通过 scanf 语句。我在 scanf 的文档中找不到任何可以表明我做错了什么的内容。我以前遇到过这个问题并且能够解决它,但我想知道发生这种情况的真正原因。我不关心检查有效的整数输入,因为我只会自己使用它,而且我知道我将输入一个整数。

【问题讨论】:

  • 如何提供输入?从键盘?
  • 在输出末尾打印换行符,即printf("Seeking for sums of %d\n",s);。另一个printf也一样。
  • 你还没有测试来自scanf()的返回值;你应该有if (scanf("%d", &amp;s) != 1) { ...handle error or EOF... }。
  • 这些循环充其量是可疑的(由于整数溢出导致的未定义行为):for(a=1; a++; a&lt;=6) { 应该是 for (a = 1; a &lt;= 6; a++) { -- 更改三次。但是玛丽安的评论是您没有看到任何输出的主要原因; printf() 在缓冲区填满或输出换行符之前不会写入屏幕。
  • 哦,天哪,非常感谢大家——我已经有一段时间没有编程了,甚至没有注意到我搞砸了循环结构。换行符让我解决了 scanf 问题,谢谢玛丽安。

标签: c integer scanf


【解决方案1】:
the following code fixes each of the problems
and not to insult georgia, but the 'georgian' method of braces is 
IMO: a clutter of the code that makes it difficult to read

#include <stdlib.h>
#include <stdio.h>

void main() 
{
    int a,b,c,s,num=0;
    printf("Enter the desired sum:");
    scanf(" %d",&s);    // note leading space in format string
    printf("Seeking for sums of %d",s);
    fflush(stdout);

    for(a=1; a++; a<6)         // note range 0...5 not 0...6
    {
        for(b=1; b++; b<6)     // note range 0...5 not 0...6
        {
            for(c=1; c++; c<6) // note range 0...5 not 0...6 
            {
                if(a+b+c==s) 
                {
                    num++;
                    printf("Die 1: %d, Die 2: %d, Die 3: %d\n",a,b,c);
                }
            }
        }
    }
}

【讨论】:

  • 在我发布问题之前,我已经尝试过 scanf 中的前导空格,但似乎并没有解决问题。玛丽安关于换行符的评论实际上是问题所在,在按照乔纳森的评论修复了循环结构之后,我的问题就解决了。不过感谢您的回答!
猜你喜欢
  • 2010-11-27
  • 1970-01-01
  • 2012-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多