2

我正在使用 Visual Studio C++。我希望能够在 double 和 long long 之间切换。如何在以下程序中使用#ifdef?我想使用更简单的解决方案来处理多个 printf 的情况。

//#define TYPE_SWITCH
#ifdef TYPE_SWITCH
      typedef double myType;
#else
      typedef long long myType;
#end

.
.
.
int main()
{
     myType a;
     #ifdef TYPE_SWITCH
        printf ("my value is %lf",a);      // I have many printf or scanf and I want to use a simple macro here
     #else
        printf ("your value is %l",a/10);      // I have many printf or scanf and I want to use a simple macro here
     #endif

}
4

1 回答 1

6

你可以使用类似的东西:

//#define TYPE_SWITCH
#ifdef TYPE_SWITCH
      typedef double myType;
      #def PATTERN_MY_TYPE "%lf"
      #def MODIFICATOR(a) (a)
#else
      typedef long long myType;
      #def PATTERN_MY_TYPE "%l"
      #def MODIFICATOR(a) (a/10)
#end
#def PATTERN_INT "%d"

//...

int main() {
     myType a;
     printf(PATTERN_MY_TYPE ", " PATTERN_INT, MODIFICATOR(a), 42);
}

编译器可以在编译时连接字符串,因此您可以使用"foo" "bar"与定义相同的方法创建字符串"foobar"。("foo" PATTERN_INT "bar"会产生"foo%dbar".

于 2013-02-04T12:27:04.160 回答