简体   繁体   中英

Write a program using conditional compilation directives to round off the number 56 to nearest fifties

Write a program using conditional compilation directives to round off the number 56 to nearest fifties.

Expected Output: 50

Where is the mistake?

#include <iostream>
using namespace std;
#define R 50
int main()
{
       int Div;
       Div = R % 50;
       cout<<"Div:: "<<Div;
       printf("\n");

#if(Div<=24)
{
       int Q;
       printf("Rounding down\n");
       Q =(int(R /50))*50;
       printf("%d",Q);
}
#else
{
       int Q;
       printf("Rounding UP\n");
       Q =(int(R/50)+1)*50;
       printf("%d",Q);
}
#endif
}

Div is a variable and so cannot be evaluated in a preprocessing directive because preprocessing happens before your source code is compiled.

Since the preprocessor does not understand variables it gives the token Div an arbitrary value of 0 when using it in an arithmetic expression. This means your program appears to work. However if you changed the value of R to say 99, you would see in that case the code does not work.

This version without Div works in all cases.

#define R 50

#if R % 50 <= 24
   int Q;
   printf("Rounding down\n");
   Q =(int(R /50))*50;
   printf("%d",Q);
#else
   int Q;
   printf("Rounding UP\n");
   Q =(int(R/50)+1)*50;
   printf("%d",Q);
#endif

It's a really, really pointless task that you have been set. I feel embarassed even attempting an answer.

The only sense-making way of interpreting the homework task is to consider 56 as an example and to require a compile-time constant result for any given integer number. The only sense-making way of using conditional compilation directives is taking also negative numbers into account.

#ifndef NUMBER
#define NUMBER  56
#endif
#if NUMBER < 0
#define ROUNDED (NUMBER-25)/50*50
#else
#define ROUNDED (NUMBER+25)/50*50
#endif

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