为什么以下代码将0作为输出

时间:2017-01-06 07:35:02

标签: c++

#include <iostream>
#include <iomanip>

using namespace std;

int main() 
{
        float a;

        float b;
        float avg;

        avg = ((3.5 * a) + (7.5 * b))/(3.5 + 7.5);

        cout <<"AVG = ";
        std::cout << std::fixed << std::setprecision(5) << avg << endl;


        return 0;
}

5 个答案:

答案 0 :(得分:5)

使用未初始化的局部变量会显示未定义的行为(UB),并且对未定义的行为有没有正确的解释

答案 1 :(得分:3)

提供 0.00000 ,因为您没有使用任何值初始化变量 a b 。 可能是您的编译器正在使用 0 初始化 a b

答案 2 :(得分:3)

以下代码肯定会产生0

        select coalesce (GROUP_CONCAT(col_name),'No_Result') into @ColumnNames
        from (
        select 'first_accuracy' as col_name, count( distinct first_accuracy) as count from compliance_employees
        where first_accuracy  is not null 
        union
        select 'second_accuracy' as col_name, count( distinct second_accuracy) from compliance_employees
        where second_accuracy  is not null
        union
        select 'third_accuracy' as col_name, count( distinct third_accuracy) from compliance_employees
        where third_accuracy  is not null
        union
        select 'fourth_accuracy' as col_name, count( distinct fourth_accuracy) from compliance_employees
        where fourth_accuracy is not null
        )a where count >0\\
        -- select @ColumnNames\\


    SET @sql := CONCAT('SELECT ', @ColumnNames, ' FROM compliance_employees');
    set @sql := REPLACE(@sql,'No_Result','"No Column have values" as No_Result')\\

     PREPARE stmt FROM @sql;
     EXECUTE stmt;          

因为#include <iostream> #include <iomanip> using namespace std; float a; float b; float avg; int main() { avg = ((3.5 * a) + (7.5 * b)) / (3.5 + 7.5); cout << "AVG = "; std::cout << std::fixed << std::setprecision(5) << avg << endl; return 0; } 类型的全局变量被编译器初始化为零。

但是您的原始代码段不正确,因为变量在操作之前未初始化 - 只是因为编译器不应该初始化此类本地变量。标准称为&#34;未定义的行为&#34;,并且一些编译器将其视为错误(例如Visual Studio C ++编译器):

  

错误2错误C4700:未初始化的本地变量&#39; a&#39; used source.cpp 15

     

错误3错误C4700:未初始化的本地变量&#39; b&#39; used source.cpp 15

第15行是float

答案 3 :(得分:1)

所以基本上这是编译器特定的东西。您的编译器似乎是将变量a和b初始化为0.理想情况下,在编译代码时应该看到一个警告,即a和b在函数main中未初始化。如果您尝试使用其他编译器,则可能不会将其分配给零,但您应该获得剩余的任何值。

答案 4 :(得分:0)

它的0是因为变量未初始化。然后它会产生未定义的行为。

如果您不知道未定义的行为是什么,那么总结一下,它只是成功构建的东西,但可执行文件并没有按照应有的方式运行。