Dok
Dok

Reputation: 71

Can someone tell me what is wrong with my code?

The code suppose to calculate price for taxi ride. For example if I ride 10 km with 2 suitcase it should print 27.2 and i get 13.00

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

#define START_PRICE 10.20;

#define PRICE_PER_KM 1.30;

#define PRICE_PER_SUITCASE 2.00;

void main()

{
    double km;

    int suitcase;

    double finalPrice;

    printf("Please enter number of kilometers: ");

    scanf("%lf", &km);

    printf("Please enter number of suitcases: ");

    scanf("%d", &suitcase);

    finalPrice = km*PRICE_PER_KM + suitcase*PRICE_PER_SUITCASE + START_PRICE;

    printf("The total price is: %.2lf\n", finalPrice);

}

Upvotes: 0

Views: 71

Answers (2)

Michi
Michi

Reputation: 5297

define is processed by the pre-processor and the compiler doesn't see these statements. So ; is not required at the end of statement.

If you turn your settings on your compiler on you will see it:

error: statement with no effect [-Werror=unused-value]|

Also you should respect the minimal standard and change your void main to int main(void){retunr 0}. And allways check the return of scanf.

This is your final program:

#include<stdio.h>

#define _CRT_SECURE_NO_WARNINGS

#define START_PRICE 10.20
#define PRICE_PER_KM 1.30
#define PRICE_PER_SUITCASE 2.00

int main(void){
    double km;
    int suitcase;
    double finalPrice;

    printf("Please enter number of kilometers: ");

    if(scanf("%lf", &km) == 1)
    printf("Please enter number of suitcases: ");

    if(scanf("%d", &suitcase) == 1)
    finalPrice = km * PRICE_PER_KM + suitcase * PRICE_PER_SUITCASE + START_PRICE;
    printf("The total price is: %.2lf\n", finalPrice);

    return 0;
}

Output:

Please enter number of kilometers: 10
Please enter number of suitcases: 5
The total price is: 33.20

Upvotes: 0

Spikatrix
Spikatrix

Reputation: 20244

Don't add semicolons at the end of lines that are too be expanded by the preprocessor.

So remove the semicolons here:

#define START_PRICE 10.20;

#define PRICE_PER_KM 1.30;

#define PRICE_PER_SUITCASE 2.00;

so that

finalPrice = km*PRICE_PER_KM + suitcase*PRICE_PER_SUITCASE + START_PRICE;

doesn't expand to

finalPrice = km*1.30; + suitcase*2.00; + 10.20;;

and instead expands to

finalPrice = km*1.30 + suitcase*2.00 + 10.20;

Upvotes: 4

Related Questions