简体   繁体   English

相同代码不同结果(C语言)

[英]Same code different results (C programming language)

This code when run in the CS50 Web IDE has expected results of running Luhn's Algorithm then correctly printing out the type of credit card used.此代码在 CS50 Web IDE 中运行时具有运行 Luhn 算法的预期结果,然后正确打印出所使用的信用卡类型。

#include <stdio.h>
#include <string.h>

int main(void){
    long ccNumber;

    do{
        printf("Insert CC Number: \n");
        scanf("%ld", &ccNumber);
    } while (ccNumber <= 0);

    long ccCopy = ccNumber;
    int sum;
    int count = 0;
    long divisor = 10;
    char result[16];

    while(ccCopy > 0){
        int lastDigit = ccCopy % 10;
        sum = sum + lastDigit;
        ccCopy = ccCopy / 100;
        printf("%i\n", sum);
    }

    ccCopy = ccNumber / 10;

    while(ccCopy > 0){
        int lastDigit = ccCopy % 10;
        int timesTwo = lastDigit * 2;
        sum = sum + (timesTwo % 10) + (timesTwo / 10);
        ccCopy = ccCopy / 100;
    }
    
    ccCopy = ccNumber;

    while(ccCopy != 0){
        ccCopy = ccCopy / 10;
        count++;
    }

    for(int i = 0; i < count - 2; i++){
        divisor = divisor * 10;
    }

    int firstDigit = ccNumber / divisor;
    int firstTwo = ccNumber / (divisor / 10);

    if(sum % 10 == 0){
        if(firstDigit == 4 && (count == 13 || count == 16)){
            strcpy(result, "VISA");
        } else if((firstTwo == 34 || firstTwo == 37) && count == 15){
            strcpy(result, "AMEX");
        } else if((firstTwo > 50 || firstTwo < 56) && count == 16){
            strcpy(result, "MASTERCARD");
        } else {
            strcpy(result, "INVALID");
        }
    }

    else {
        strcpy(result, "INVALID lol");
    }

    printf("%i\n", sum);
    printf("%s\n", result);
   
}

The issue is, when copy and pasted into VSCode the Sum is not calculated the same问题是,当复制并粘贴到 VSCode 中时,Sum 的计算方式不同

These are the results from CS50 IDE:这些是 CS50 IDE 的结果:

Insert CC Number: 
4012888888881881,
1,
9,
17,
25,
33,
41,
43,
43,
90,
VISA

And these are the results from VSCode with the exact same code copy and pasted:这些是 VSCode 使用完全相同的代码复制和粘贴的结果:

Insert CC Number: 
4012888888881881,
15774464,
15774472,
15774480,
15774488,
15774496,
15774504,
15774506,
15774506,
15774553,
INVALID lol

The original code did not have the printf showing sum in the first while loop I added it to debug the results.原始代码在第一个 while 循环中没有显示总和的printf我添加它是为了调试结果。

This has left me very confused, considering the code is copy and pasted.考虑到代码是复制粘贴的,这让我很困惑。

sum is not initialized to 0 , so you are having undefined behaviour. sum未初始化为0 ,因此您有未定义的行为。 Then you get different results depending on compiler, platform, weather....然后你会根据编译器、平台、天气……得到不同的结果。

You need to initialize all variables.您需要初始化所有变量。 int sum can be anything. int sum可以是任何东西。

Initialize sum to 0.sum初始化为 0。

 int sum = 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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