简体   繁体   中英

Smallest of three numbers using macro MINIMUM3

I have to create a code that determines the smallest of three numeric values. Macro MINIMUM3 should use macro MINIMUM2 (the difference btwn two numeric values) to determine the smallest number. the input values come from the user input. I am not very familiar with using macros and my textbook doesn't really help in showing me an example of how they can work together to carry out their function. The code below is the work in progress that I have so far but I am running into errors on lines 3, 13, 16, and 20.

#define MINIMUM2 (a,b) (a < b ? a:b)

#define MINIMUM3 (a,b,c) (MINIMUM2(a,b) c? MINIMUM (a,b) :c)

int main (void) {
    int x,y,z;
    int temp; 
    printf("Please enter three numbers\n");
    scanf("%d%d%d, &x&y&z);
    temp = MIN(x,y,z);
    printf("The smallest number entered is:\n");
    printf("%d", &temp);
    getchar ();
    return0;
}

You have a couple of issues in your code:

  • MINIMUM3 uses MINIMUM instead of MINIMUM2
  • The logic of MINIMUM3 is broken
  • You need to remove spaces after macro names
  • You are missing a closing double quote and commas in call of scanf
  • You are using MIN in place of MINUMUM3
  • You are passing an address of temp to printf

Here is how you can fix this:

#define MINIMUM2(a,b) (a < b ? a:b)
#define MINIMUM3(a,b,c) (MINIMUM2(MINIMUM2(a,b),c))

int main (void) {
    int x,y,z;
    int temp; 
    printf("Please enter three numbers\n");
    scanf("%d%d%d", &x, &y, &z);
    temp = MINIMUM3(x, y, z);
    printf("The smallest number entered is:\n");
    printf("%d", temp);
    getchar ();
    return0;
}

Demo.

You can improve your macros by enclosing each parameter in parentheses:

#define MINIMUM2 (a,b) ((a) < (b) ? (a) : (b))

Your definition of the MINIMUM3 macro will lead to a syntax error. You should try something like

#define MINIMUM3(a, b, c) MINIMUM2(MINIMUM2(a, b), c)

or

#define MINIMUM3(a, b, c) MINIMUM2(a, MINIMUM2(b, c))

Also make sure to call MINIMUM3 in main , not MIN .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM