亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

objective-c - 請大家?guī)臀铱纯礊槭裁催@段代碼一直是死循環(huán)(obejective-c)
黃舟
黃舟 2017-04-21 11:17:44
0
2
520

當輸入不滿足第一個if語句的條件時,不是理想的重新給type1和type2賦值而是死循環(huán)。

#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
    @autoreleasepool {
        //6.5.1
        long int type1, type2, flag=0;
        printf("請輸入要測試的兩個整數(shù):");
        while (flag==0) {
            scanf("%li %li", &type1, &type2);
            if( (type1 ==(long int) type1) && (type2 ==(long int) type2) && type2 != 0){

                if( type1 % type2 == 0 ){
                    printf("%li可以被%li整除", type1, type2);
                    flag=1;
                }else{
                    printf("%li不可以被%li整除", type1, type2);
                    flag=1;
                }

            }else{
                printf("只能輸入整數(shù),并且第二個數(shù)不能為0,請重新輸入:");
            }
        }
        return 0;
    }
}
黃舟
黃舟

人生最曼妙的風(fēng)景,竟是內(nèi)心的淡定與從容!

reply all(2)
伊謝爾倫

You need to judge the return value of scanf to see if there is illegal input. If there is illegal input, you must first clear the previously entered content, for example, use this code:

if (scanf("%li %li", &type1, &type2) != 2) { // illegal input
    int ch; 
    while ((ch = getchar()) != '\n' && ch != EOF) {
        // intend to be blank
    }
}

Of course, it is generally believed that scanf不太安全,因此至少都應(yīng)該用fgets以及sscanfRewritten:


char buffer[256];
if (fgets(buffer, sizeof(buffer), stdin) == NULL) {
    // error or no more to read
    // ...
}

if (sscanf(buffer, "%li %li", &type1, &type2) != 2) { // illegal input
    // print error message
    // continue
    // ...
}

PS. (type1 ==(long int) type1) && (type2 ==(long int) type2) This sentence is quite redundant.

迷茫

This is a C problem not an Objective-c problem.

If scanf encounters illegal input, it will fail to execute, but the illegal input will still remain in the buffer. When scanf requests input again, it will directly read the buffer without waiting for terminal input.

The solution has been given by Theo.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template