【问题标题】:How to add variable inside the cout?如何在 cout 中添加变量?
【发布时间】:2020-02-05 11:13:00
【问题描述】:

我想在 cout 中添加浮点平均变量。 什么是最完美的方式?

int first , second , third;
cout<<"enter the first number: ";
cin>>first;
cout<<"enter the second number: ";
cin>>second;
cout<<"enter the third number: ";
cin>>third;

cout<<float average=(first+second+third)/3;

【问题讨论】:

标签: c++ variable-declaration


【解决方案1】:

C++ 方式是:

float average = static_cast<float>(first + second + third) / 3.;
std::cout << average << std::endl;

【讨论】:

  • 加法可能溢出,加法前最好先除法。
【解决方案2】:

你不能那样做。只需在打印之前声明变量即可。

float average = (first + second + third) / 3;
std::cout << average;

但是,您可以做的就是根本没有变量:

std::cout << (first + second + third)/3;

还要注意(first+second+third)/3 的结果是int 并将被截断。如果您不打算这样做,您可能需要将 int first, second, third; 更改为 float first, second, third;

【讨论】:

    【解决方案3】:

    float average=(first+second+third)/3; cout<<average

    cout&lt;&lt;((first+second+third)/3)

    【讨论】:

      【解决方案4】:

      你需要先声明变量类型。

      你可以这样做。

      int first , second , third;
      cout<<"enter the first number: ";
      cin>>first;
      cout<<"enter the second number: ";
      cin>>second;
      cout<<"enter the third number: ";
      cin>>third;
      
      float average;
      
      cout<< (average=(first+second+third)/3);
      

      【讨论】:

        猜你喜欢
        • 2020-12-03
        • 2017-09-11
        • 2018-10-05
        • 2022-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多