如何在cout中添加变量?
How to add variable inside the cout?
我想在 cout 中添加 float average 变量。
什么是完美的方式?
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++ 方式为:
float average = static_cast<float>(first + second + third) / 3.;
std::cout << average << std::endl;
你不能那样做。只需在打印前声明变量即可。
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;
。
float average=(first+second+third)/3;
cout<<average
或者
cout<<((first+second+third)/3)
您需要先声明变量类型
你可以这样做。
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);
我想在 cout 中添加 float average 变量。 什么是完美的方式?
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++ 方式为:
float average = static_cast<float>(first + second + third) / 3.;
std::cout << average << std::endl;
你不能那样做。只需在打印前声明变量即可。
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;
。
float average=(first+second+third)/3;
cout<<average
或者
cout<<((first+second+third)/3)
您需要先声明变量类型
你可以这样做。
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);