Hi i am a beginner and i have been trying to solve this set but with no avail.
I tried to use what was taught in the first lesson and did search for some help online when i encounter errors. However, i am still unable to execute the code properly. What may have gone wrong?
The question apparently require me to check if the credit card number is valid. First I want to make sure the credit card number consist of 16digits, then I tried to identify the respective digits. I then multiply the alternate numbers starting from second last digit by 2. After which I tried to identify any 2digits value (e.g 18) from the multiplied result and sum it (eg 1+8). Then add the sum of the another set of alternate digits with the sum of the multiplied amount. And if the last digit of the sum=0, then it should return approve.
I managed to get no error for my codes but it keeps giving me “disapprove” even if the credit card number should return “approve” please help thank you.
this is my code:
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int count=0;//no. of digits
int sum1=0;
int sum2;
int sum3;
int main(void)
{
long long cc = 0;
do
{
printf ("please input your credit card no. \n cc.:"); // prompt
cc=get_long_long();}
while (cc< 0);
//determine if it has valid number of digits
long long digits = cc;
while (digits>0)
{
digits/=10;
count++;
}
if (count!=16)
{printf("invalid\n");
}
else{
for(int i=1;i<=count; i++)
{ double a=0;
double b=0;
a+= pow(10,i);
b+= pow(10,(i-1));
long long c;
long long d;
c=a;//convert double to int so % can be used
d=b;
if(i%2==0)//identify even position digits
{
int even_digits;
int xsum=0;
even_digits=2*(((cc%c)-(cc%d))/d); //2* even position digits
if(even_digits>9)//identify 2 digits values after 2* e.g. 18
{
xsum+=(even_digits/10)+(even_digits%10);//sum the 2 value digits e.g. 1+8=9
}
else
{ sum1+=even_digits; } //sum of all the even position digits that has only 1 value
sum2=sum1+ xsum;//sum of all the even position digits
}
else
{
int odd_digits=0;
odd_digits=((cc%c)-(cc%d))/d;//identify all value of odd position digits
sum3= sum3+odd_digits;//sum all values on odd position
}}
int sum4=0;
sum4 = sum3+sum2; //sum of even and odd position digits
if(sum4%10==0)
{
printf("approve\n");
}
else
{
printf("disapprove\n");
}
}
}