简体   繁体   English

C printf中的输出

[英]OUTPUT in C printf

What's the meaning of -6i in this code? 这段代码中的-6i是什么意思?

#include<stdio.h>

int main()
{
    int i = 1234;
    printf("%d",-6i);
}

To answer your real question, -6i is a complex constant (a GCC extension). 为了回答您的真实问题, -6i是一个复数常数(GCC扩展名)。 From http://gcc.gnu.org/onlinedocs/gcc/Complex.html : http://gcc.gnu.org/onlinedocs/gcc/Complex.html

To write a constant with a complex data type, use the suffix 'i' or 'j' (either one; they are equivalent). 要编写具有复杂数据类型的常量,请使用后缀'i'或'j'(二者之一;它们等效)。 For example, 2.5fi has type _Complex float and 3i has type _Complex int . 例如, 2.5fi具有_Complex float类型, 3i具有_Complex int类型。 Such a constant always has a pure imaginary value, but you can form any complex value you like by adding one to a real constant. 这样的常数总是具有纯虚数,但是您可以通过将一个常数添加到实数来形成任意复杂的值。 This is a GNU extension; 这是GNU扩展; if you have an ISO C99 conforming C library (such as GNU libc), and want to construct complex constants of floating type, you should include <complex.h> and use the macros I or _Complex_I instead. 如果您具有符合ISO C99的C库(例如GNU libc),并且想要构造浮点型的复杂常量,则应包括<complex.h>并改用宏I_Complex_I

So the i in -6i has nothing to do with the variable i , just like the f in the float constant -1.0f would have nothing to do with a variable named f . 因此, -6ii与变量i无关,就像浮点常量-1.0ff与名为f的变量无关。

A a side note, printf("%d",-6i); 旁注printf("%d",-6i); is undefined behavior, since the format spec %d doesn't deal with complex arguments. 是未定义的行为,因为格式规范%d不会处理复杂的参数。 GCC doesn't make any promises (as far as I know) about the representation of a complex type. 就我所知,GCC并没有对复杂类型的表示做任何承诺。 You can't say much of anything about what that printf() would do. 关于printf()会做什么,您不能说太多。

I think that to print the complex value, you'd have to extract each component of the complex value separately (I don't think glibc's printf() has a format spec extension that deals with GCC's complex types). 我认为要打印复杂值,您必须分别提取复杂值的每个组成部分(我不认为glibc的printf()具有处理GCC复杂类型的格式规范扩展名)。 Something like: 就像是:

printf("%d %d\n",__real__ -6i, __imag__ -6i);
printf("%f %f\n",__real__ -6.i, __imag__ -6.i);

Maybe if you change you code a little bit: 也许如果您更改代码,可能会:

int main(){
   int i = 1234;
   printf("%d",-6*i); 
   }

You may get -7404 back. 您可能会收到-7404

And to answer the second question, please check this question . 并回答第二个问题,请检查此问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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