CS50 PSET 1黑客不良信用代码 [英] CS50 PSET 1 hacker bad credit code
本文介绍了CS50 PSET 1黑客不良信用代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目标是查找信用卡号码是否有效。
完整说明此处:
问题集1:C [ ^ ]
我能否知道是什么让我的代码失败?
(我没有运行错误)
我尝试过:
The goal is to find if a credit card number is valid.
Complete Instructions Here:
Problem Set 1: C[^]
Can I please know what makes my code fail?
(I dont get running errors)
What I have tried:
#include <stdio.h>
include <cs50.h>
include <stdlib.h>
include <ctype.h>
include <string.h>
include <math.h>
int main(void) {
char name[20]; char dist[3]; long long number = GetLongLong();
sprintf(name, "%lld", number );
int length = strlen(name);
if ( (length != 13) || (length != 15) || (length != 16) ) { printf("INVALID"); return 1; }
int SUM = 0; if ( (length == 13) || (length == 15) ) { for (int a = 1; a < length-1; a+=2) { int prodig = (name[a]-48)* 2; sprintf(dist, "%d", prodig); if (strlen(dist) == 2) { SUM = SUM + (dist[0]-48) + (dist[1]-48); } else { SUM += prodig; } }
for (int a = 0; a < length; a+=2)
{
SUM += (name[a]-48);
}
}
if (length == 16) { for (int a = 1; a < 17; a+=2) { int prodig = (name[a]-48)* 2; sprintf(dist, "%d", prodig); if (strlen(dist) == 2) { SUM = SUM + (dist[0]-48) + (dist[1]-48); } else { SUM += prodig; } }
for (int a = 0; a < 15; a+=2)
{
SUM += (name[a]-48);
}
}
if (SUM%10 != 0) { printf("INVALID"); return 1; }
else { if (name[0] == 3) { printf("AMEX"); }
else if (name[0] == 5)
{
printf("MASTERCARD");
}
else
{
printf("VISA");
}
}
return 0;
}
推荐答案
使用调试器。这就是它的一部分。
在函数的开头放置一个断点,然后仔细查看正在发生的事情。
但首先要帮自己一个忙,然后格式化你的代码,使其缩进一致 - 这样可以更容易地看到它发生了什么。
一旦你知道发生了什么,以及为什么会出错,这应该是相当明显的。
Use the debugger. That's part of what it is there for.
Put a breakpoint at the start of the function, and step through look at closely at what is going on.
But do yourself a favour first, and format your code so it's indented consistently - it makes it a lot easier to see what it happening.
It should be reasonably obvious once you get into it what is happening, and why it's going wrong.
这篇关于CS50 PSET 1黑客不良信用代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文