user2278764 - 1 year ago 120
C Question

Pointers in C not working as desired

I'm trying to work through Harvard's CS50 problem set and I find myself stuck on a very basic greedy problem of finding the least number of coins for given change if the coins are only available in denominations of 25c, 10c, 5c and 1c. While pointers are not really needed for this problem and even having a separate function is an overkill probably, I'm trying to get a better understanding of pointers by implementing it here, however, I don't get the desired output for 'coins' for some reason. The printf statements after before and after function calls are for debugging purposes. A sample output is given after the code.

Here's the code:

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

void denomination(float* change, int* coins, int den);

int main(void){

float change;
do{
printf("How much change is owed?\n");
change = GetFloat();
}while(change < 0);

int coins; //number of coins in total to be given in change

if(change == 0){
coins = 0;
printf("%d\n", coins);
}else{
change = change * 100; //converting to cents
denomination(&change, &coins, 25);
printf("Inside else:: Change: %f, Coins: %d\n", change, coins);
denomination(&change, &coins, 10);
printf("Inside else:: Change: %f, Coins: %d\n", change, coins);
denomination(&change, &coins, 5);
printf("Inside else:: Change: %f, Coins: %d\n", change, coins);
denomination(&change, &coins, 1);
printf("Inside else:: Change: %f, Coins: %d\n", change, coins);
printf("%d\n", coins);
}
return 0;
}

void denomination(float* change, int* coins, int den){
int tmp;
tmp = (*change/den);
printf("Temp: %d\n", tmp);
*coins = *coins + tmp;
*change = *change - (tmp*den);
}
``````

Here's the output:

``````How much change is owed?
0.41
Temp: 1
Inside else:: Change: 16.000000, Coins: 134516108
Temp: 1
Inside else:: Change: 6.000000, Coins: 134516109
Temp: 1
Inside else:: Change: 1.000000, Coins: 134516110
Temp: 1
Inside else:: Change: 0.000000, Coins: 134516111
134516111
``````

I don't understand why 'change' works as desired but 'coins' does not.

First of remove the while loop in function.

``````void denomination(float* change, int* coins, int den)
{
int tmp;
tmp = (*change/den);
printf("Temp: %d\n", tmp);
*coins = *coins + tmp;
*change = *change - (tmp*den);
}
``````

Because you are already dividing so getting the total number of coins only in one time.

So first of all there is no need of loop.

Then instead of only removinf one den you have to remove total amount which will be multiple of tmp coins to be given.

So Corrected the following statement in your function.

``````*change=(*change-(tmp*den));
``````

Second thing initialize the coins variable.

As i think it is giving somewhat garbage value.

So initialize it with zero in main.

``````int Coins=0;
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download