【问题标题】:C program that uses functions to verify security codes使用函数验证安全代码的 C 程序
【发布时间】:2021-12-04 15:16:57
【问题描述】:

我正在尝试编写一个使用 Luhn 算法来验证安全代码的程序。程序需要:

从文件中读取安全码并将其输入到数组中

使用一个功能读取安全码

使用另一个函数来验证它们

为了验证它们,奇数位的数字将被加在一起。偶数位的数字将乘以 2;一旦它们乘以 2,如果数字小于 10,则将其添加到偶数的总和中;如果大于十,则将数字的数字之和添加到偶数之和中。因此,如果数组中第二个位置的数字是 8,则将其乘以 2 得到 16,然后将 1 + 6 = 7 添加到偶数的总和中。验证代码还有更多工作要做,但这是我现在正在处理的部分。

我遇到的问题:我认为我从文件中扫描代码的功能不正确。文件中的每个代码都有 20 位数字,所以当我声明数组变量时,我做了:int sc[20]。但是,有不止一个 20 位数的安全码,我不知道如何解决。

第二个:我不知道如何处理对偶数求和的第二部分(如果数字乘以 2 大于 10,则将其数字添加到偶数的总和中)。

这是文件的前几行(整个文件很长,所以我只列出前几行):

0 7 6 1 1 6 6 2 6 8 5 1 5 5 7 7 7 8 0 2 

2 5 1 6 2 1 8 2 4 3 0 9 1 9 1 1 3 1 3 8
 
1 3 3 4 5 4 5 2 8 6 1 8 9 3 7 6 2 2 0 5 

到目前为止,这是我的代码:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>

ReadSecurityCode(FILE* codes, int sc[]);

int main(void) {
    int sc[20], i;
    FILE* codes;

    codes = fopen("SecurityCodes.txt", "r");

    while (fscanf(codes, "%c\n", &sc) != EOF) {
        ReadSecurityCode(codes, sc[20]);
    }

    fclose(codes);
    return(0);
}


int ReadSecurityCode(FILE* codes, int sc[]) {
    int i;
    for (i = 0; i < 20; i++) {
        fscanf(codes, "%d", &sc[i]);
    }
    return(sc[20]);
}


int isCodeValid(int sc[]) {
    int i, sumodds = 0, sumevens = 0, sumtotal;
    for (i = 1; i < 20; i = i + 2) {
        sumodds = sumodds + sc[i];
    }
    
    for (i = 0; i < 20; i = i + 2) {
        sc[i] = sc[i] * 2;
        if (sc[i] < 10) {
            sumevens = sumevens + sc[i];
        }
        else {

        }
    }
    return(sumtotal);
}

【问题讨论】:

  • 您的问题包含sn-ps代码,分享minimal reproducible example会更有帮助。这是算法在各种语言中的实现geeksforgeeks.org/luhn-algorithm
  • 1) 你的原型应该包括 "int": int ReadSecurityCode(FILE* codes, int sc[]);, 2) 你应该检查每个 fscanf() 的返回值以防读取错误, 3) 你覆盖数组 sc 每个循环时,4)您根本不会调用 IsCodeValid()
  • 1 位数字小于 4 位信息 (log2(10 == 3.3) 。考虑使用 char (sizeof(char) == 1) 而不是 int (sizeof(int) 可能是8 在您的平台上)每个数字。
  • 同时在你的编译器上调高警告级别。它会告诉你变量i 没有在main() 中使用。 fopen() 可能会失败,因此请检查返回码。
  • 在提高警告级别后,您可能还会收到一些警告,指出&amp;sc 没有适合格式说明符%c 的类型

标签: c function file


【解决方案1】:

最简单的选择是随时阅读和验证每一行。在您发布的代码中,这意味着在您读取记录的 while 循环中调用 isCodeValid()

    while (fscanf(codes, "%c\n", &sc) != EOF) {
        ReadSecurityCode(codes, sc);
        isCodeValid(sc);
    }

考虑使用 char 而不是 int 来存储每个数字(即char sc[20])。

不确定为什么 ReadSecurityCode 返回第一个元素,但 scanf() 可能会失败,因此您可能希望返回错误代码并检查它。另外,我建议您使用ReadSecurityCode() 来读取包含换行符的行。

您可能还想根据isCodeValid() 的返回值做一些事情。 is-naming 建议您返回一个布尔值,但您返回的是一个总和。

根据以上建议,应该是:

   while (!ReadSecurityCode(codes, sc)) {
      if (!isCodeValid(sc)) {
           printf("%s is invalid\n", sc);
      }
   }

【讨论】:

    猜你喜欢
    • 2016-06-15
    • 2016-02-21
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 2011-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多