在while循环时,使用逗号表达式遇到的问题
话不多说
题目描述
温度有两种表示方法:华氏温度与摄氏温度,请编写一个程序,要求使用面向对象编程,定义两个类分别表示两种数据,使用类型转换的方法,实现两种温度的类型之间的相互转换,摄氏温度为c,其与华氏温度f之间的转换公式为f=c*9/5+32。
输入
输入第一行为一个字母(若为’c’则表示接下来输入的数据为摄氏温度,若为’f’则表示接下来输入的数据为温度)
接下来有多个实数输入
输出
若输入的数据为摄氏温度,则输出其对应的华氏温度,反之亦然,要求每个数据占一行,且以4舍5入的形式保留3位小数
#include<iostream>
using namespace std;
class temperature{
public:
temperature(double d){
c=d;
}
temperature(temperature &obj){
c=obj.c;
}
void change_one(double k){
c=k;
f=c*9/5+32;
cout.setf(ios::fixed);
cout.precision(3);
cout<<f<<endl;
}
void change_twe(double k){
f=k;
c=(f-32)*5/9;
cout.setf(ios::fixed);
cout.precision(3);
cout<<c<<endl;
}
private:
double f;
double c;
};
int main(){
double d;
temperature t1(0);
char f;
cin>>f;
if(f == 'c'){
while(cin>>d,d!=EOF){
temperature t2(t1);
t2.change_one(d);
}
}
else if(f == 'f'){
while(cin>>d,d!=EOF){
temperature t3(t1);
t3.change_twe(d);
}
}
return 0;
}
结果使用ctrl+z结束循环时,程序并没有结束,反而一直打印最后结果
当我没有使用逗号表达式时,程序OK没问题
#include<iostream>
using namespace std;
class temperature{
public:
temperature(double d){
c=d;
}
temperature(temperature &obj){
c=obj.c;
}
void change_one(double k){
c=k;
f=c*9/5+32;
cout.setf(ios::fixed);
cout.precision(3);
cout<<f<<endl;
}
void change_twe(double k){
f=k;
c=(f-32)*5/9;
cout.setf(ios::fixed);
cout.precision(3);
cout<<c<<endl;
}
private:
double f;
double c;
};
int main(){
double d;
temperature t1(0);
char f;
cin>>f;
if(f == 'c'){
while(cin>>d){//不要使用逗号表达式
temperature t2(t1);
t2.change_one(d);
}
}
else if(f == 'f'){
while(cin>>d){
temperature t3(t1);
t3.change_twe(d);
}
}
return 0;
}