【问题标题】: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<<((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);