[英]C get every other digit from an int
I'm following CS50 course of Harvard University and I have to create a program in C that finds if a credit card number is valid or not.我正在学习哈佛大学的 CS50 课程,我必须用 C 创建一个程序来查找信用卡号是否有效。 For example, I want from this number 378282246310005 to get the every other digit like this 7224300 so I started like this:
例如,我想从这个数字 378282246310005 得到像这个 7224300 这样的每隔一个数字,所以我是这样开始的:
printf("Number\n");
long long cardNum = GetLongLong();
I don't know the methods I need to use to get the other digits to make my calculations.我不知道我需要使用哪些方法来获取其他数字来进行计算。
One way to do it would be like this:一种方法是这样的:
int digits[7]; // storage for odd digits
cardNum /= 10; // throw away the least significant digit
for (int i = 0; i < 7; ++i) // for each odd digit
{
digits[i] = cardNum %10; // extract the digit
cardNum /= 100; // throw away two digits
}
Make use of simple division (/) and % operator to get this使用简单的除法 (/) 和 % 运算符来获得它
int number[20];
int count = 0;
long long cardNum = GetLongLong();
long long prevNum = cardNum;
while (cardNum < 10)
{
cardNum = prevNum / 10;
number[count] = prevNum % 10;
prevNum = cardNum;
count++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.