Erlang Start![1]

练习链接: http://erlang.org/course/exercises.html

题目:

Simple sequential programs

1. Write functions temp:f2c(F) and temp:c2f(C) which convert between centigrade and Fahrenheit scales. (hint 5(F-32) = 9C)

2. Write a function temp:convert(Temperature) which combines the functionality of f2c and c2f. Example:

    > temp:convert({c,100}).
=> {f,212}
> temp:convert({f,32}).
=> {c,0}
回答:
%% Author: Quon
%% Created: 2009-8-6
%%File: temp.erl
-module(temp).
-export([f2c/1,c2f/1,convert/1]).

%Ex1
f2c(F) 
->
  (
5*(F-32))/9.
  
c2f(C) 
->
  
9*C/5+32.

%Ex2
convert({c, C}) 
->
  {f, 
9*C/5+32};

convert({f, F}) 
->
  {c, (
5*(F-32))/9}.

更新:
发现一点小错误,默认的"/"操作符的结果是浮点数,如果需要输出整数,需要用div操作符,正确的结果为:
%% Author: Quon
%% Created: 2009-8-6
%%File: temp.erl
-module(temp).
-export([f2c/1,c2f/1,convert/1]).

%Ex1
f2c(F) 
->
  (
5*(F-32)) div 9.
  
c2f(C) 
->
  
9*C div 5+32.

%Ex2
convert({c
, C}) ->
  {f
, 9*C div 5+32};

convert({f
, F}) ->
  {c
, (5*(F-32)) div 9}.

posted on 2009-08-07 10:13  Quon Lu  阅读(188)  评论(0编辑  收藏  举报

导航