更改函数中整数的值

Changing a value of an integer in a function

我对函数 'multiply2' 有疑问,它不会将 ccn1 的值更改为 ccn8。它必须将它们乘以 2,如果结果等于或大于 10,则取该方程的乘积并将它们相加(即 7 * 2 = 14,因此 1 + 4 = 5)。整个事情会起作用,但我注意到函数 'multiply2' 将 pX 的值保留给它自己,我想覆盖 ccn1 到 ccn8 的值,然后将所有值加在一起(ccn1 到 ccn16 ).请帮忙 :( PS:我是新手,所以请保持温和,我敢肯定这对你来说看起来很乱。

程序按原样编译,没有错误,请注意,它确实包含 cs50.h 库 "get_long_long" 函数,提示用户输入信用卡号

我尝试过使用指针,但显然我没有完全理解这个概念!我已经设法取消引用 *pX,它分配了 ccn1、ccn2 等值,但它们仍然没有在 main 中更新。

此处描述的整个问题:https://docs.cs50.net/2018/x/psets/1/credit/credit.html#tl-dr

谢谢!

# include <cs50.h>
# include <stdio.h>
# include <math.h>

void multiply2 (int * pX);

long long ccn;


//a program to check the credit card number and print out if it's  American Express, Visa, or MasterCard. if else - ILVALID.
int main(void)
{
//prompt user for a credit card number
ccn = get_long_long("Number: ");

//every second digit starting from second to last
int ccn1 = (ccn % 100) / 10;
int ccn2 = (ccn % 10000) / 1000;
int ccn3 = (ccn % 1000000) / 100000;
int ccn4 = (ccn % 100000000) / 10000000;
int ccn5 = (ccn % 10000000000) / 1000000000;
int ccn6 = (ccn % 1000000000000) / 100000000000;
int ccn7 = (ccn % 100000000000000) / 10000000000000;
int ccn8 = (ccn % 10000000000000000) / 1000000000000000;
//printf("%i\n%i\n%i\n%i\n%i\n%i\n%i\n%i\n", ccn1, ccn2, ccn3, ccn4, ccn5, ccn6, ccn7, ccn8);

//all the other digits
int ccn9 = (ccn % 10);
int ccn10 = (ccn % 1000) / 100;
int ccn11 = (ccn % 100000) / 10000;
int ccn12 = (ccn % 10000000) / 1000000;
int ccn13 = (ccn % 1000000000) / 100000000;
int ccn14 = (ccn % 100000000000) / 10000000000;
int ccn15 = (ccn % 10000000000000) / 1000000000000;
int ccn16 = (ccn % 1000000000000000) / 100000000000000;
//printf("%i\n%i\n%i\n%i\n%i\n%i\n%i\n%i\n", ccn9, ccn10, ccn11, ccn12, ccn13, ccn14, ccn15, ccn16);



if (((ccn >= 340000000000000 && ccn <= 349999999999999) || (ccn >= 370000000000000 && ccn <= 379999999999999)) ||
    ((ccn >= 5100000000000000 && ccn <= 5199999999999999) || (ccn >= 5500000000000000 && ccn <= 5599999999999999)) ||
    ((ccn >= 4000000000000 && ccn <= 4999999999999) || (ccn >= 4000000000000000 && ccn <= 4999999999999999)))
{
    multiply2(&ccn1);
    multiply2(&ccn2);
    multiply2(&ccn3);
    multiply2(&ccn4);
    multiply2(&ccn5);
    multiply2(&ccn6);
    multiply2(&ccn7);
    multiply2(&ccn8);


    int sum = (ccn1 + ccn2 + ccn3 + ccn4 + ccn5 + ccn6 + ccn7 + ccn8 + ccn9 + ccn10 + ccn11 + ccn12 + ccn13 + ccn14 + ccn16);
    printf("%i\n", sum);


}

/NOTHING FROM ABOVE - INVALID
else
{
    printf("INVALID\n");
}



}

void multiply2 (int * pX)
{
if ((*pX *2) >= 10)
{
    *pX = ((*pX * 2) % 10) + 1;
    printf("%i\n", *pX);
}
else
{
    printf("%i\n", (*pX * 2));
}
}

您的函数 multiply2 仅在其值至少为 5 的情况下才更改传递参数的值。
试试这个:

void multiply2(int* pX)
{
  *pX = *pX * 2; /* Multiply value by 2 */
  if (*pX >= 10)
    *pX = (*pX % 10) + 1; /* Adjust if value greater than or equal to 10 */
  printf("%d\n", *pX);
}