Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

c - how to get the intended result when the second input b equals 0?

When I ran this code and provided 28000/3 as input, it showed:

28000/32766 = 0.

Why on earth would this happen? I'm new to c and this is really confusing.

#include <stdio.h>

int main(void) {
    int divide(int a, int b, int *result);
    int a, b;
    
    scanf("%d %d", &a, &b);
    
    int c;
    
    if (divide(a, b, &c)) {
        printf("%d/%d=%d
", a, b, c);
    }
    
    return 0;
}

int divide(int a, int b, int *result) {
    int ret = 1;
    if (b == 0) 
        ret = 0;
    else {
        *result = a / b;
    }
    return ret;
}
question from:https://stackoverflow.com/questions/66058117/how-to-get-the-intended-result-when-the-second-input-b-equals-0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The scanf() doesn't know if you would enter a division sign /. You need to change its format:

scanf("%d/%d", &a, &b);

So that you could enter 28000/3 or similar inputs.


Here's the perfect code (notice comments):

#include <stdio.h>
#include <limits.h>

// Definitions must be global
int divide(int a, int b, int *result);

int main(void) {
    int a, b;

    // It's programmer's responsibility to ensure the input
    if (scanf("%d/%d", &a, &b) != 2) {
        puts("Arguments are incorrectly passed.");
        return -1;
    }

    int c;

    if (divide(a, b, &c))
        printf("%d/%d=%d
", a, b, c);
    else
        printf("b is zero.
"); // also code the 'else' to print an error
                                // if b is zero

    return 0;
}

int divide(int a, int b, int *result) {
    int ret = 1;
    if (b == 0 || (a == INT_MIN && b == -1))
        ret = 0;
    else
        *result = a / b;
    
    return ret;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...