English 中文(简体)
遇到困难
原标题:Having difficulties dereferencing a pointer in C

我的任务是起草一份方案,向用户询问他们需要多少钱,然后向用户询问他们想要购买多少票。 我必须具备主要()职能和采购标的功能。 我对点人来说是新鲜事,在如何利用这些变量分配当地变量和利用这些当地变量进行计算方面,我感到非常困惑。 我能否了解一下我究竟是哪里错了,以及如何把这变成一个可贵的方案?

EDIT:必须有两个功能:主票和购票。 如果用户没有足够的钱购买票,则需要使用变数剩余现金的点子,方案必须退还零。

#include <stdio.h>

#define ADULT_TICKET_PRICE 69.00                                                    //define constants
#define CHILD_TICKET_PRICE 35.00

int PurchaseTickets(double *pRemainingCash, int adultTickets, int childTickets);    //declare function PurchaseTickets()

int main(void)
{
    double funds;
    int childTickets;
    int adultTickets;

    printf("How much money do you have to purchase tickets?
");
    if(scanf("%lf", &funds) != 1)                        //check for errors in user input
    {
        printf("Invalid input, exiting program.
");
        return 1;                                       //will exit program if invalid characters are entered
    }

    printf("How many child tickets would you like to purchase?
");
    if(scanf("%d", &childTickets) != 1)                 //check for errors in user input
    {
        printf("Invalid input, exiting program.
");
        return 1;                                       //will exit program if invalid characters are entered
    }

    printf("How many adult tickets would you like to purchase?
");
    if(scanf("%d", &adultTickets) != 1)                 //check for errors in user input
    {
        printf("Invalid input, exiting program.
");
        return 1;                                       //will exit program if invalid characters are entered
    }

    double *pfunds = &funds;

    PurchaseTickets(pfunds, adultTickets, childTickets);

    return 0;
}

/*****************************************************************************************
 *
 *  Function:  PurchaseTickets()
 *
 *  Parameters:
 *
 *      pRemainingCash - points to a variable containing the amt of cash from user
 *      adultTickets - specifies the number of adult tickets the user wants to buy
 *      childTickets - specifies the number of child tickets the user wants to buy
 *
 *  Description: 
 *
 *      The function will determind if the user has enough money to purchase the
 *      specified number of tickets. If they do, the function deducts the proper funds
 *      from their remaining cash and returns the total number of tickets purchased.
 *      if they do not the function returns 0.
 *
*****************************************************************************************/

int PurchaseTickets(double *pRemainingCash, int adultTickets, int childTickets)
{
    double adultCost = (adultTickets * ADULT_TICKET_PRICE);
    double childCost = (childTickets * CHILD_TICKET_PRICE);
    double totalCost = adultCost + childCost;

    int totalTickets = adultTickets + childTickets;

    double remainingCash = *pRemainingCash;
    pRemainingCash = &remainingCash;

    pRemainingCash = remainingCash - totalCost;


    if (*pRemainingCash >= totalCost)
    {
        printf("You have purchased %d tickets, and you have %.2f remaining.",totalTickets, pRemainingCash);
    }

    else
    {
        printf("You do not have enough money to purchase the tickets.");
        return 0;
    }

    return 1;
}
问题回答

我审查了你的法典,从我可以认为是理想的解决办法来看,实际上不需要点人来开展这一方案。 首先,由于“火焰火焰”功能并未真正恢复任何必要的信息,因此更有必要以一个真空的返回条目来设置这种功能。 其次,由于这一职能所需的投入变量只能作为数值通过,因此实际上没有必要发送点名。

为了尽量减少对你的法典的起码改动,可以在你的职能中发表以下声明,同时重述“印本”声明。

    //double remainingCash = *pRemainingCash;           // Not needed
    //pRemainingCash = &remainingCash;

    //pRemainingCash = remainingCash - totalCost;


    if (*pRemainingCash >= totalCost)
    {
        printf("You have purchased %d tickets, and you have %.2f remaining.",totalTickets, *pRemainingCash - totalCost);    // Note remainder calculation
    }

这在码头产生了以下试验产出。

craig@Vera:~/C_Programs/Console/TicketPurchase/bin/Release$ ./TicketPurchase 
How much money do you have to purchase tickets?
800
How many child tickets would you like to purchase?
4
How many adult tickets would you like to purchase?
4
You have purchased 8 tickets, and you have 384.00 remaining.

Noting the observations of the code and simplifying things, following is a refactored version of your program.

#include <stdio.h>

#define ADULT_TICKET_PRICE 69.00                                                    //define constants
#define CHILD_TICKET_PRICE 35.00

void PurchaseTickets(double pRemainingCash, int adultTickets, int childTickets);    //declare function PurchaseTickets()

int main(void)
{
    double funds;
    int childTickets;
    int adultTickets;

    printf("How much money do you have to purchase tickets? ");
    if(scanf("%lf", &funds) != 1)                       //check for errors in user input
    {
        printf("Invalid input, exiting program.
");
        return 1;                                       //will exit program if invalid characters are entered
    }

    printf("How many child tickets would you like to purchase? ");
    if(scanf("%d", &childTickets) != 1)                 //check for errors in user input
    {
        printf("Invalid input, exiting program.
");
        return 1;                                       //will exit program if invalid characters are entered
    }

    printf("How many adult tickets would you like to purchase? ");
    if(scanf("%d", &adultTickets) != 1)                 //check for errors in user input
    {
        printf("Invalid input, exiting program.
");
        return 1;                                       //will exit program if invalid characters are entered
    }

    PurchaseTickets(funds, adultTickets, childTickets);

    return 0;
}

/*****************************************************************************************
 *
 *  Function:  PurchaseTickets()
 *
 *  Parameters:
 *
 *      pRemainingCash - points to a variable containing the amt of cash from user
 *      adultTickets - specifies the number of adult tickets the user wants to buy
 *      childTickets - specifies the number of child tickets the user wants to buy
 *
 *  Description:
 *
 *      The function will determind if the user has enough money to purchase the
 *      specified number of tickets. If they do, the function deducts the proper funds
 *      from their remaining cash and returns the total number of tickets purchased.
 *      if they do not the function returns 0.
 *
*****************************************************************************************/

void PurchaseTickets(double pRemainingCash, int adultTickets, int childTickets)
{
    double adultCost = (adultTickets * ADULT_TICKET_PRICE);
    double childCost = (childTickets * CHILD_TICKET_PRICE);
    double totalCost = adultCost + childCost;

    int totalTickets = adultTickets + childTickets;

    pRemainingCash -= totalCost;

    if (pRemainingCash >= 0.00)
    {
        printf("You have purchased %d tickets, and you have %.2f remaining.
",totalTickets, pRemainingCash);
    }

    else
    {
        printf("You do not have enough money to purchase the tickets.
");
    }

    return;
}

注:

  • The return value for the "PurchaseTickets" function was changed to "void" since there appears to be no use for an integer return value.
  • All variables are passed as values in lieu of using any variable pointers.
  • Unneeded variables were removed to simplify calculations and comparisons.

经过这些改进,对该方案和机票购买功能进行了一系列额外测试。

craig@Vera:~/C_Programs/Console/TicketPurchase/bin/Release$ ./TicketPurchase 
How much money do you have to purchase tickets? 300.00
How many child tickets would you like to purchase? 4
How many adult tickets would you like to purchase? 4
You do not have enough money to purchase the tickets.
craig@Vera:~/C_Programs/Console/TicketPurchase/bin/Release$ ./TicketPurchase 
How much money do you have to purchase tickets? 600
How many child tickets would you like to purchase? 4
How many adult tickets would you like to purchase? 4
You have purchased 8 tickets, and you have 184.00 remaining.

概括而言,通过可变的地址而不是职能中可变的数值,是有正当理由的,但应始终认识到确定是否需要这种功能的背景。 或许应当就确定何时点人受益的职能寻求更多的指导。

这是一个泥土。 在不重复@NoDakker的评论的情况下,下文是显示所需业务的缩略本。 注意一些变数已重新命名(并删除评论),以提高清晰度。

// heading stuff omitted for brevity
int main(void)
{
    double funds;
    int childTickets;
    int adultTickets;

    /* Get funds */ // omitted for brevity

    /* Get # of Child tickets */

    /* Get # of Adult tickets */

    int totTckts = PurchaseTickets( &funds, adultTickets, childTickets );

    // Notice that the function performs its task.
    // Reporting those results belongs in the calling function
    if( totTckts )
        printf( "%d tickets, and you have %.2f remaining.", totTckts, funds );
    else
        printf( "Insufficient funds to purchase those tickets." );

    return 0;
}

int PurchaseTickets( double *pFunds, int nAdult, int nChild )
{
    double Cost
        = (nAdult * ADULT_TICKET_PRICE)
        + (nChild * CHILD_TICKET_PRICE);

    if( *pFunds < Cost ) // Insufficient available funds?
        return 0; // no show

    *pFunds -= Cost; // subtract cost from "double funds;" variable in main()

    return nAdult + nChild; // return # of purchased tickets
}




相关问题
Fastest method for running a binary search on a file in C?

For example, let s say I want to find a particular word or number in a file. The contents are in sorted order (obviously). Since I want to run a binary search on the file, it seems like a real waste ...

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

Tips for debugging a made-for-linux application on windows?

I m trying to find the source of a bug I have found in an open-source application. I have managed to get a build up and running on my Windows machine, but I m having trouble finding the spot in the ...

Trying to split by two delimiters and it doesn t work - C

I wrote below code to readin line by line from stdin ex. city=Boston;city=New York;city=Chicago and then split each line by ; delimiter and print each record. Then in yet another loop I try to ...

Good, free, easy-to-use C graphics libraries? [closed]

I was wondering if there were any good free graphics libraries for C that are easy to use? It s for plotting 2d and 3d graphs and then saving to a file. It s on a Linux system and there s no gnuplot ...

Encoding, decoding an integer to a char array

Please note that this is not homework and i did search before starting this new thread. I got Store an int in a char array? I was looking for an answer but didn t get any satisfactory answer in the ...

热门标签