Home > other >  C function does not show anything
C function does not show anything

Time:11-11

I'm new to c and I'm trying to make a function to return the max between two numbers, and I don't know why it does not work, it does not show anything

int max(int num1, int num2) {

   int result;

   if (num1 > num2)
      result = num1;
   else
      result = num2;
 
   return result; 
}


int main()
{
   int result = max(1,2);

   printf("%c", result);

}

CodePudding user response:

Small error very last line:

Use "%d" instead of "%c" as your output is an integer and not a character.

printf("%d", result);

Tip, you may add "\n" at the end which will create a new line on the terminal.

printf("max is %d\n", result);

CodePudding user response:

You are using %c in your print. %c is used for print char data type (character). %f for float data type. %i or %d is used for int data type (integer). Secondly, you are missing return 0; in the end of your function.

Correct code

#include <stdio.h>

int max(int num1, int num2) {
  int result;
  if (num1 > num2)
    result = num1;
  else
    result = num2;
  return result;
}
int main() {
  int result = max(1, 2);

  printf("%d", result);
  return 0;
}

CodePudding user response:

Here you have made a mistake in the print statement. To print an Integer you need to type "%d" instead of %c. This should fix it.

%c prints a Character; %d prints an Integer

You can refer to this page https://www.tutorialspoint.com/c_standard_library/c_function_printf.htm

  •  Tags:  
  • c
  • Related