如何从 C 函数中返回多个计数器变量
我对 C 编程还很陌生,如果我在任何时候听起来不对劲,请多多包涵。我试图返回两个 int 变量,另一个函数需要它们的值。
这是我想要的一个想法:
#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 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
sumCardDigit
函数的末尾有一些问题:函数的末尾应如下所示:
现在您的代码应该可以编译,但我不知道代码是否确实正确。
There are a few problems at the end of your
sumCardDigit
function:The end of the function should look like this:
Now your code should compile, but I don't know if the code is actually correct.