0

My program is supposed to take num (number of clients that'll have a discount calculated for), than it goes into 'for' and starts the loop of asking the clients name (char name) and how much he spent on the store (float value), and calculates the discount. The problem is, it is printing trash values before printing the right ones.

#include <stdio.h>
int main()
{
    int num = 0, i = 0;
    char name = '\0';
    float value = 0.0;
    scanf("%d", &num);

    for (i = 0; i < num; i++)
    {
        scanf("%c %f", &name, &value);

        if (value < 500)
        {
            value = value / 10;
            printf("\nClient %c has a %.3f$ bonus!\n", name, value);
        }
        else
        {
            value = value / 100 * 15;
            printf("\nClient %c has a %.3f$ bonus!\n", name, value);
        }
    }

    return 0;
}

If I insert name and value, it'll first print the initial values of my variables first. What is going on here? How can I fix it?

Lia Mart
  • 1
  • 1
  • 2
    Are you sure you want to scan just single letter names? `char name` hasn't room for more – and not even that if you want to null-terminate, too. – Aconcagua May 24 '22 at 09:57
  • @Lia Mart Use scanf(" %c %f", &name, &value);. See the leading space in the format string. It allows to skip white space characters. – Vlad from Moscow May 24 '22 at 09:58
  • Yeah, just a single letter. – Lia Mart May 24 '22 at 09:58
  • 2
    You should check the result of `scanf`, it should match the number of scanned arguments – if not, some input has gone wrong. – Aconcagua May 24 '22 at 10:00
  • To clarify the previous comment: You should check the "return value" of `scanf` (the word "result" is ambiguous, as it could also mean the result of the conversion). – Andreas Wenzel May 24 '22 at 11:04

0 Answers0