while循环逗号表达式

在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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值