-3

结果看起来像错误!窗口 10 和 ubuntu 中的代码结果不同,因为我预期的结果是:

如果输入 5;预期结果(它在 ubunt 中工作)

5 数字 5

不能被 3 整除。

5(在 Windows 10 中工作)数字 5 - 35

能被 3 整除。

在 Visual Studio 中(Cl.exe 退出代码 2)

我不知道为什么在我的结果中附加了 -35 并且计算错误!

在窗口 10 中 eclipse cygwin gcc

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

struct digit
{
    int num;
    struct digit *next;
};
struct digit *createDigit(int dig);
struct digit * append(struct digit * end, struct digit * newDigptr);
void printNumber(struct digit *start);
struct digit *readNumber(void);
void freeNumber(struct digit *start);
int divisibleByThree(struct digit *ptr);

int main(void) {

    struct digit *start;
    start = readNumber();

    printf("The number ");
    printNumber(start);
    if (divisibleByThree(start))
        printf("is divisible by 3.\n");
    else
        printf("is not divisible by 3.\n");
    freeNumber(start);
    return 0;
}

struct digit *createDigit(int dig) {
    struct digit *ptr;
    ptr = (struct digit *) malloc(sizeof(struct digit));
    ptr->num = dig;
    ptr->next = NULL;
    return ptr;
}

struct digit * append(struct digit * end, struct digit * newDigptr) {
    end->next = newDigptr;
    return(end->next);
}

void printNumber(struct digit *start) {
    struct digit * ptr = start;
    while (ptr!=NULL) {
        printf("%d", ptr->num);
        ptr = ptr->next;
    }
    printf("\n");
}

void freeNumber(struct digit *start) {
    struct digit * ptr = start;
    struct digit * tmp;
    while (ptr!=NULL) {
        tmp = ptr->next;
        free(ptr);
        ptr = tmp;
    }
}


struct digit *readNumber(void) {
    char c; // read character
    int d;
    struct digit *start, *end, *newptr;
    start = NULL;
    scanf("%c", &c);
    while (c != '\n') {
        d = c - 48; // character to integer
        newptr = createDigit(d);
        if (start == NULL) {
            start = newptr;
            end = start;
        } else {
            end = append(end, newptr); // linked to each other
        }
        scanf("%c", &c);
    }
    return(start);
}

int divisibleByThree(struct digit *start){
    struct digit *ptr = start;
    int i = ptr->num;
    int divisible = 3;
    while( ptr->next!= NULL){
        i = ptr->next->num + (i % divisible)*10;
        ptr = ptr->next;
    }
    //printf("\n%d\n",i);
    if(i % divisible) return 0;
    else return 1;

}

5 数字 5 不能被 3 整除。 5 数字 5 - 35 可以被 3 整除。

4

1 回答 1

4

在 Windows 上,你似乎读到了一个\r-35,因为\r它的值为 13。

您需要确保不在列表中包含非数字。

所以改变

while (c != '\n') {

while (isdigit(c)) {

或者如果您想手动检查(而不是使用isdigit

while (c >= '0' && c <= '9') {

注意:isdigit需要#include <ctype.h>

Linux 和 Windows 上的不同结果是因为它们对“换行符”的定义不同。Linux 只使用“\n”,而 Windows 使用“\r\n”

于 2019-06-11T13:06:52.067 回答