I am very new to programming with C, please do bear with me if I sound off at any point. I am trying to return two int variable, whose values are required in another function.
here is an idea of what I want :
#include <cs50.h>
#include <stdio.h>
typedef struct {
int sum,digit;
}twoInts ;
// prototype functions
twoInts sumCardDigit(long d);
int main(void)
{
//digit below is used to check for even and other positions
long cardNum = get_long("Enter card number :");
twoInts values = sumCardDigit(cardNum);
printf("values: %d\n",values.sum)
}
twoInts sumCardDigit(long cardNum)
{
int sumeven = 0, sumodd = 0,digit = 0, sum = 0;
int rem = cardNum % 10;
digit ;
//if digit is even
if (digit % 2 == 0)
{
int multiply = rem * 2;
if (multiply == 0)
{
sumeven = multiply;
}
else
{
//adding all digits after
while (multiply != 0)
{
sumeven = multiply % 10;
//minus last digit of multiply
multiply /= 10;
}
}
}
else //if digit is odd
{
sumodd = rem;
}
//minus last digit from cardNum
cardNum /= 10;
sum = sumeven sumodd;
struct twoInts s;
s.sum;
s.digit
}
return s;
}
I want a situation where both the sum and digit's value can be used elsewhere in my program.
CodePudding user response:
There are a few problems at the end of your sumCardDigit
function:
The end of the function should look like this:
...
sum = sumeven sumodd;
twoInts s; // remove `struct`, twoInts has been typedefed so it's
// wrong to use struct
s.sum = sum; // you forgot the assignment
s.digit = digit; // you forgot the assignment
// there was a `}` thet didn't belong here
return s;
}
Now your code should compile, but I don't know if the code is actually correct.
CodePudding user response:
You can only return one thing at a time in C. The method you follow is correct one of using a struct. Wherever you are using these value, you will have to get both sum and digit from this struct.