I wrote the following code to try to find the first digit of a long number (this is for the CS50x "Credit" exercise), but it's not working. Any tips?
// Conditions and relational operators
#include <stdio.h>
#include <cs50.h>
#include <unistd.h>
#include <math.h>
// Main programme
int main(void)
{
int sum0 = 0;
//Prompt for card number
long cardnumber = get_long("Enter credit card number: ");
//find first digit as part of validity check
int getfirstdigit = cardnumber;
while (getfirstdigit >= 10)
{
sum0 = getfirstdigit / 10;
}
}
The code's compiling, and I'm using printf("first digit: %i\n", sum0);
to see what the process is returning. Each time it returns 0
. (I thought maybe it might be because I'm converting a long
into an int
, but when getfirstdigit
is a long
the programme doesn't work at all (i.e., I have other code after this that's carrying out other processes, which works, ordinarily; but nothing happens at all if getfirstdigit
is a long
.)
What might be going on? Thanks!
(My reasoning for the code is that the credit card number is divided by 10 over and over again to keep removing the last digit until only the first remains.)