在Matlab中,有两个求正弦的函数:sin()、sind()
其中,函数sin(x)里x的单位为弧度rad,sind(y)里y的单位为度数°。如果弧度用r标记,角度用d标记,那么
30弧度 = 30r = 30 * 180/π = 30 * 57.3 = 1719度 = 1719°
30角度 = 30d = 30°
SIN(30r) = sind(30r) = sind(1719°) =-0.988
SIN(30d) = sind(30°) = 0.5
编写一个实现,输入xxxR、xxxD能够根据后缀R、D,分别采用sin()、sind()计算正弦值的.m文件:
//angle_dr
% Prompt the user for angle and 'd' for degrees
% or 'r' for radians; print the sine of angle
% Read in the response as a string and then
% separate the angle and character
degrad = input('Enter angle and d/r: ','s');
angle = degrad(1:length(degrad)-1);
dorr = degrad(end);
% Error~check to make sure user enters 'd' or 'r'
%while (dorr ~= 'd' && dorr ~= 'D') && (dorr ~= 'r' && dorr ~= 'R')
while strcmpi(dorr,'d')~=1 && strcmpi(dorr,'r')~=1
disp('Error! Enter d or r with the angle.')
degrad = input('Enter angle and d/r: ','s');
angle = degrad(1:length(degrad)-1);
dorr = degrad(end);
end
% Convert angle to number
anglenum = str2num(angle);
fprintf('The sine of %.1f ',anglenum)
% Choose sin or sind function
% ingore Upper and Lower
if strcmpi(dorr, 'd')
fprintf('degrees is %.3f.\n',sind(anglenum))
else
fprintf('radians is %.3f.\n',sin(anglenum))
end
效果如下: