1

Question:

If cost price and selling price of an item is input through the keyboard, write a program to determine whether the seller has made profit or incurred loss. Also determine how much profit he made or loss incurred.

Here is my code:

#include <stdio.h>

int main() {
    int x, y, z, b, n;
    char k = '%';
    char r = '$';
    printf("Enter cost of item:-");
    scanf("%d", &x);
    printf("Enter selling price of item:-");
    scanf("%d", &y);
    if (x < y) {
        n = y - x;
        z = 100 / x;
        b = n / z;
        printf("You made %d%c profit \n", b, k);
        printf("or\n");
        printf("%d %c profits\n", n, r);
    }
    if (x > y) {
        n = y - x;
        z = 100 / x;
        b = n / z;
        printf("You made %d%c loss \n", b, k);
        printf("or\n");
        printf("%d %c loss\n", n, r);
    }
    return 0;
}

Hey I'm new in C programming knows basic only. Today I'm learning if / else and I try to solve this question. But my code not giving any error and warning. It takes input and after its end my if not working. please Help:(

  • 2
    What does "not working" mean? Does it crash? Does it print wrong numbers? No output at all? Please edit your question to include a detailled description of your problem. Also add sample input, output and expected output. – Gerhardh Apr 06 '23 at 11:16
  • 2
    Side note: Pretty poor variable names – avoid inexpressive single character identifiers (unless for a few exceptions like `x` and `y` being coordinates e.g. on the screen, or `i`, `j` for loop variables, ...). Instead give them proper names indicating what they serve for (e.g. `buyPrice` and `sellPrice` or at least `buy` and `sell`). Once your code gets more complex you'll otherwise end up in hell looking forwards and backwards all the time to determine which variable has been used for which purpose. – Aconcagua Apr 06 '23 at 11:26
  • `z = 100/x; b = n/z;` <=> `b = n/(100/x)` <=> `b = n*x/100` – even if there wasn't a problem with integer division this would't yield the results you want... Instead: `percent = (y - x) * 100/x` would do the trick(rounded towards zero); by multiplying first you avoid truncating the result too early; if you want to apply commercial rounding you can have `((y - x) * 100 + x / 2) / x`. – Aconcagua Apr 06 '23 at 11:34
  • And before you try with `double` to get decimal places rather calculate in integrals in appropriate precision, i.e. in 10th, 100th, ... of a percent, which would look for 10th as: `permille = ((y - x) * 1000 + x / 2) / x;` together with `printf("%d.%d%%", permille / 10, permille % 10)` – because you do not have precise math with floating point types (even simple numbers like `0.1` or `0.7` cannot be represented exactly as they are periodic in binary). – Aconcagua Apr 06 '23 at 11:43
  • For e.g. 100th make sure to print two digits for the decimals not to make 0.05 ressemble 0.5 by use of the appropriate format spedifier: `%d.%.2d%%`). – Aconcagua Apr 06 '23 at 11:52
  • 1
    @Aconcagua is right. This variable naming method you have (or don't have) is going to come back to bite you if you don't start using proper names. – Div Apr 06 '23 at 11:59

2 Answers2

1

There is a problem here:

    z = 100 / x;
    b = n / z;

If the price x is larger than 100, z will have the value 0 because of integer division semantics and n / z will cause undefined behavior because of division overflow, which may cause the program to stop.

Here are my recommendations:

  • avoid dividing by zero
  • use floating point arithmetics to avoid excessive rounding.
  • use explicit names to make your program easier to read and understand.
  • test the return value of scanf() to detect invalid or missing input.

Here is a modified version:

#include <stdio.h>

int main(void) {
    int cost, sale;

    printf("Enter cost of item: ");
    if (scanf("%d", &cost) != 1) {
        printf("input error!\n");
        return 1;
    }
    printf("Enter selling price of item: ");
    if (scanf("%d", &sale) != 1) {
        printf("input error!\n");
        return 1;
    }
    if (cost == 0) {
        printf("no cost base, total profit of $%d\n", sale);
    } else
    if (cost == sale) {
        printf("it's a wash: no profit, no loss\n");
    } else
    if (cost < sale) {
        int profit = sale - cost;
        int margin = profit * 100 / cost;
        printf("You made a %d%% profit of $%d\n", margin, profit);
    } else {
        int loss = cost - sale;
        int margin = loss * 100 / cost;
        printf("You made a %d%% loss of $%d\n", margin, loss);
    }
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • OP says the program just hangs. Won't a zero division simply cause a floating point exception at runtime and exit? – Tasos Papastylianou Apr 06 '23 at 11:47
  • @TasosPapastylianou There's no floating point involved – and for integers division by zero is UB... – Aconcagua Apr 06 '23 at 12:04
  • @Aconcagua interesting, I wasn't aware of this distinction. When I run the code on my machine I get a floating point exception; are you saying that this is the result of undefined behaviour rather than a true floating point exception? – Tasos Papastylianou Apr 07 '23 at 23:08
  • Ah, nevermind, this covers it well: https://stackoverflow.com/a/54488609/4183191 Thanks for the tip! – Tasos Papastylianou Apr 07 '23 at 23:15
0

Here. is the complete answer. for you. have have make mistake in calculation

#include <stdio.h>

int main() {
    float x, y, z, b, n;
    char k = '%';
    char r = '$';
    printf("Enter cost of item: ");
    scanf("%f", &x);
    printf("Enter selling price of item: ");
    scanf("%f", &y);
    if (x <= y) {
        n = y - x;
        z = n/x*100;
      
        printf("You made %f %c profit \n", z, k);
        printf("or\n");
        printf("%f %c profits\n", n, r);
    }
    if (x > y) {
        n = x-y;
        z = n/x*100;
        printf("You made %f%c loss \n", z, k);
        printf("or\n");
        printf("%f %c loss\n", n, r);
    }
    return 0;
}
Engr.Aftab Ufaq
  • 3,356
  • 3
  • 21
  • 47
  • *have make mistake* – you, too!!! Assume `x == 100` and `y == 120`, yielding `n == 20` – what will `n/x` (`20/100`) result in? – Aconcagua Apr 06 '23 at 11:47
  • please read it carefully. it will be 20/100*100 – Engr.Aftab Ufaq Apr 06 '23 at 15:29
  • And that's the problem – it is integer division, thus 20/100 results in 0 – any fractional part is lost. You avoid if you first multiply by 100 and only afterwards divide by x, though this corresponds to rounding towards zero, rounding commercially would require adding an appropriate offset of x/2 before division. – Aconcagua Apr 07 '23 at 20:27
  • please check the datatypes they are float – Engr.Aftab Ufaq Apr 07 '23 at 20:29
  • Ah, OK, this change I indeed didn't notice – but that makes the issue even worse. There's no exact math with floating point, even such simple numbers like 0.1, 0.2 or 0.7 cannot be represented exactly as they are periodic in binary. If you fall back to, at least use `double` for better precision (there's almost never a reason to use `float` unless perhaps on a MCU when needing to store many values in an array), but if possible (and it is here) better avoid entirely. – Aconcagua Apr 07 '23 at 20:34
  • Some implications of floating point e.g. [here](https://stackoverflow.com/questions/588004/is-floating-point-math-broken/) or [here](https://stackoverflow.com/questions/4915462/how-should-i-do-floating-point-comparison) – and you can find quite some more, try e.g. `stackoverflow c floating point compare epsilon` in your favourite search engine... – Aconcagua Apr 07 '23 at 20:35