Can some help me with my Default:

It is printing the error message but at end of message is giving a decimal value for the char sign.

How do I stop this from happening?

#include <stdio.h>
char sign;
int x, y;

int main() {
  printf("Choose:\n");
  printf("a) Addition\n");
  printf("b) Subtraction\n");
  printf("c) Division\n");
  printf("d) Multiplication\n");
  scanf("%c", &sign);
  sign = 'f';  // For testing the Default
  printf("Enter two numbers:\n");
  scanf("%d%d", &x, &y);
  x = 12; // Test for x
  y = 4; // Test for y
  /*Print out their numbers inside the math_function*/
  printf("%d\n", math_function(x, y));
  return 0; 
}
int math_function(int x, int y) {
  switch(sign) {
    case 'a':
      return x + y;
    case 'b':
      return x - y;
    case 'c':
      return x / y;
    case 'd':
      return x * y;
    default:
      printf("'%c' is an invalid choice ", sign);
  }
  return 0;
}

Recommended Answers

All 4 Replies

I get the following output:

'f' is an invalid choice 0

which looks like it doesn't give a decimal value for the char sign. It gives an 'f'.

Ahh yes, sorry, I was meaning that '0' after the message. Is there a way to lose that?

That's being printed by this line:

printf("%d\n", math_function(x, y));

If you don't always want to print out the return value from the function math_function, store the return value instead of printing it, and then check it; if it's zero, don't print it.

Of course, this means that if the answer ever IS actually zero, you wouldn't print it, so you'd be better off instead having some mechanism by which the function indicates success or failuire as well as giving you the value. I would suggest something like have the function return success or failure, and one of its inputs is a pointer to an int in which to put the answer.

Thank you Moschops, I completely ignored my printf in main. I've just added a simple:

if (sign == 'a' || sign == 'b' || sign == 'c' || sign == 'd')
  printf("%d\n", math_function(x, y));
else
  printf("'%c' is an invalid choice ", sign);
return 0; 

and in the Switch Default: removed the printf and replaced with break;

Problem now resolved

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.