我对函数“multiple2”有问题,它不会将ccn1的值更改为ccn8。它必须将它们乘以2,如果结果等于或大于10,则取此方程的乘积并将它们相加(即7*2=14,所以1+4=5)。整个过程都可以,但是我注意到函数'multiple2'将pX的值保持为自身值,我想覆盖ccn1到ccn8的值,然后将所有值相加(ccn1到ccn16)。请帮忙:(
附言:我是新来的,所以请你温柔一点,我相信你会觉得一团糟。
该程序编译时没有错误,请注意,它确实包含cs50.h库,用于“get_long_long”功能,提示用户输入信用卡号码
我试过使用指针,但显然我不完全理解这个概念!我已经设法解除了对指定ccn1、ccn2等值的*pX的引用,但它们在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);
}

关于c - 在函数中更改整数值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53871467/

10-13 07:10