Objective-C实现摄氏温度和华氏温度互转(附完整源码)
发布日期:2025-04-26 00:18:53 浏览次数:2 分类:精选文章

本文共 1399 字,大约阅读时间需要 4 分钟。

Objective-C 实现摄氏温度与华氏温度互转

以下是一个简单的 Objective-C 程序,用于实现摄氏温度与华氏温度之间的互相转换。该程序提供一个简单的命令行界面,让用户可以输入要转换的温度和转换方向。
完整代码示例
#import   
@interface TemperatureConverter : NSObject
- (double)celsiusToFahrenheit:(double)celsiusTemperature;
- (double)fahrenheitToCelsius:(double)fahrenheitTemperature);
@end
int main(int argc, char **argv) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// 检查命令行参数
if (argc != 3) {
NSLog(@"使用说明: %s
<温度>
<转换方向>
\n", argv[0]);
return EXIT_FAILURE;
}
double temperature = atof(argv[1]);
NSString *direction = argv[2];
if (!direction || [direction length] != 2) {
NSLog(@"错误:转换方向必须是 'C' 或 'F'\n");
return EXIT_FAILURE;
}
double convertedTemp;
if ([direction isEqualToString:@"C"]) {
convertedTemp = [converter celsiusToFahrenheit:temperature];
} else {
convertedTemp = [converter fahrenheitToCelsius:temperature];
}
NSLog(@"转换结果: %.6f\n", convertedTemp);
[pool release];
return EXIT_SUCCESS;
}
@implementation TemperatureConverter
- (double)celsiusToFahrenheit:(double)celsiusTemperature) {
return (celsiusTemperature * 9/5) + 32;
}
- (double)fahrenheitToCelsius:(double)fahrenheitTemperature) {
return (fahrenheitTemperature - 32) * 5/9;
}
@end
关键词:[Objective-C, 温度转换, 摄氏温度, 华氏温度, 命令行程序]
上一篇:Objective-C实现播放器(附完整源码)
下一篇:Objective-C实现插值查找算法(附完整源码)

发表评论

最新留言

关注你微信了!
[***.104.42.241]2025年04月24日 19时18分33秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章