簡體   English   中英

C ++:名稱空間和printf vs cout中的extern變量

[英]C++ : extern variable inside namespace and printf vs cout

我的printf有點問題,我也不知道為什么!

=> kernel.h當

#ifndef KERNEL_H
#define KERNEL_H

namespace kernel
{
    extern const double h;
}

#endif // KERNEL_H

=> kernel.cpp

#include <kernel.h>

namespace kernel
{
    const double kernel::h=85.0;
}

=>的main.cpp

#include "kernel.h"
#include <iostream>
//#include <cstdio>//With cstdio, it is the same problem !

int main(int argc, char *argv[])
{

    using namespace kernel;

    double a = h;

    printf("printf a is %d\n",a);
    std::cout<<"std::cout a is " << a << std::endl;

    printf("printf h is %d\n",h);
    printf("printf kernel::h is %d\n",kernel::h);
    std::cout << "std::cout h is " << h << std::endl;

    return 0;
}

我在控制台上的輸出是:

printf a is 0
std::cout a is 85
printf h is 0
printf kernel::h is 0
std::cout h is 85

為什么printf不起作用? 因為它是C函數?

謝謝

%d是整數,您正在嘗試將double打印為int 我想您想讓%lf雙倍的long float嗎? 從未真正打印過兩倍。

那是因為您將其打印為integer 嘗試%lg%lf

printf("printf kernel::h is %lg\n",kernel::h);

如果您打開警告 ,編譯器會告訴您問題所在。 -Wformat

或僅使用std::cout ,您就不會遇到此類問題

std::cout << kernel::h;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM