简体   繁体   中英

Using scanf() to obtain a single integer

I'm just using this small program to save myself from iterating through all the possible combinations of three dice on paper. It accepts an input using scanf() and then checks every combination to see if the sum of the dice is the provided number.

#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);
                }
            }
        }
    }
}

The problem is, the program doesn't proceed past the scanf statement. I can't find anything in the documentation for scanf that would suggest what I'm doing wrong. I have run into this issue before and was able to get around it, but I would like to know the real reason why this occurs. I am not concerned about checking for valid integer input as I will only use this myself and I know that I will be inputting an integer.

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);
                }
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM