【发布时间】:2023-03-31 02:23:01
【问题描述】:
我正在开发一个程序,用于检查我正在参加的 CS50 课程的信用卡号码的有效性(我发誓这是合法的哈哈),我目前正在努力正确获取每个 CC 的前两个号码#检查它来自哪个公司。为了清楚起见,我评论了每个部分的作用,并评论了我的问题出现的地方。
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <math.h>
#include <string.h>
int main(void)
{
long long ccn = get_long_long("Enter CCN: \n");
int count = 0;
long long ccn1 = ccn;
// finds the amount of digits entered and stores that in int count.
while (ccn1 != 0)
{
ccn1 /= 10;
+count;
}
printf("%i \n", count);
// ln 17- 19 should take int count, subtract two, put that # as the power of 10,
// then divide the CC# by that number to get the first two numbers of the CC#.
long long power = count - 2;
// here is where i get the error. its a long long so it
// should hold up to 19 digits and im only storing 14 max
// but it says that 10^14th is too large for type 'int'
long long divide = pow(10,power);
long long ft = ccn / divide;
printf("power: %i \n", power); //ln 20-22 prints the above ints for debug
printf("Divide: %lli \n", divide);
printf("First two: %lli \n", ft);
string CCC;
// ln 24-35 cross references the amount of digits in the CC#
// and the first two digits to find the comapany of the credit card
if ((count == 15) && (ft = 34|37))
{
CCC = "American Express";
}
else if ((count == 16) && (ft = 51|52|53|54|55))
{
CCC = "MasterCard";
}
else if ((count = 13|16) && (ft <=49 && ft >= 40))
{
CCC = "Visa";
}
printf("Company: %s\n", CCC);
}
【问题讨论】:
-
使用
pow进行整数计算是个坏主意。 -
不是你的问题,但你可能不想使用这个:
else if ((count == 16) && (ft = 51|52|53|54|55))。首先,|是按位或不合逻辑的,您应该使用||并且您不能以您所做的方式链接它。而=是赋值运算符,而不是相等。 -
从一个初学者到另一个,你的猜测和我的一样好在C语言中,这意味着我们的两个猜测都可能是错误的,即使我们观察它们“起作用”,因为即使是早期的细微错误也意味着我们研究的整个基础都建立在错误的假设之上。因此,作为初学者,我们需要一种不同的方法来确保我们教科书的有效性。
标签: c variables cs50 long-long