Home > Back-end >  Cs50 Week1 Cash test
Cs50 Week1 Cash test

Time:08-31

'Im working on cs50 week 1 "cash" when i test the code the tool is working but when i submit it in the Website it's got errors and i don't know why i will add me code here'

#include<stdio.h>
#include<cs50.h>
#include<math.h>
int main(void){
 int changeswhithcustomer;
do{
     changeswhithcustomer = get_int("how much changes you want to exchange ? ");
}while(changeswhithcustomer < 0);
int coins = 0;
while(changeswhithcustomer >= 25){
  changeswhithcustomer = changeswhithcustomer - 25;
    coins  ;
}
while(changeswhithcustomer >= 10){
  changeswhithcustomer = changeswhithcustomer - 10;
    coins  ;
}
while(changeswhithcustomer >= 5){
  changeswhithcustomer = changeswhithcustomer - 5;
    coins  ;
}
while(changeswhithcustomer >= 1){
  changeswhithcustomer = changeswhithcustomer - 1;
    coins  ;
}
printf("%i\n",coins);
}

CodePudding user response:

Your program may compile but it's non-sense. Your input runs in a loop till negative which then does nothing. You use a single counts variable for each denomination but you want a variable per coin. Here is data driven approach using a coins array to hold each coin's face value and count:

#ifdef CS50_POLYFILL
int get_int(const char *s) {
    printf("%s", s);
    int i;
    scanf("%d", &i);
    return i;
}
#else
#include <cs50.h>
#endif
#include <stdio.h>

unsigned change(unsigned amount, unsigned face_value, unsigned *count) {
    for(*count = 0; amount >= face_value; (*count)  )
        amount -= face_value;
    return amount;
}

int main(void) {
    struct {
        unsigned face_value;
        unsigned count;
    } coins[] = {
        { .face_value = 25 },
        { .face_value = 10 },
        { .face_value = 5 },
        { .face_value = 1 },
    };
    int amount = get_int("how much changes you want to exchange? ");
    if(amount < 0)
        return 0;
    for(unsigned i = 0; i < sizeof(coins) / sizeof(*coins); i  ) {
        amount = change(amount, coins[i].face_value, &coins[i].count);
        if(coins[i].count)
            printf("face value %u: count: %u\n",
                coins[i].face_value,
                coins[i].count
            );
    }
    return 0;
}

and example run:

how much changes you want to exchange? 73
face value 25: count: 2
face value 10: count: 2
face value 1: count: 3

CodePudding user response:

From the spec

Is check50 failing to compile your code?

CS50x 2022’s version of Cash is quite different than CS50x 2021’s version. Last year’s version will fail to compile when checked by check50 (but not necessarily if you run it yourself, assuming your file consists of legal C code) due to the fact that in this new version you must implement five functions which the testing suite will test independently, beyond just checking for the final answer (as last year’s version did).

See the spec to download the correct distribution code.

  • Related