If statements and strcmp function

7 次查看(过去 30 天)
Given: strcmp = matching case, strcmpi=ignoring case
Find: Prompt user to enter an angle; prompt user to determine if the angle was provided in degrees or radians; write an if statement that calculates the sine of the angle using the sin function if the units were in radians or sind if the units were degrees.
Issue: I created a flow chart, wrote my code, but it's not giving me what I want, grrrrr. Shows the same output for degrees and radians.
My solution:
angle=input('Enter an angle: ');
units=input('Is it in degrees or radians? ','s');
if sin(angle) % if 45 degrees should be 0.0123413415 radians
fprintf('The sine of your angle is %3.1f %s.\n',sin(angle),units)
elseif sind(angle) % if 45 degrees should be sqrt(2)/2=0.7071
fprintf('The sine of your angle is %3.1f %s.\n',sind(angle),units)
end

采纳的回答

Hassaan
Hassaan 2024-3-21
angle = input('Enter an angle: ');
units = input('Is it in degrees or radians? ', 's');
% Normalize the case of the user input for units to ensure case-insensitive comparison
units = lower(units);
% Compare the input string for units and compute the sine accordingly
if strcmp(units, 'radians')
% User specified radians, use sin function
result = sin(angle);
fprintf('The sine of your angle in radians is %.4f.\n', result);
elseif strcmp(units, 'degrees')
% User specified degrees, use sind function
result = sind(angle);
fprintf('The sine of your angle in degrees is %.4f.\n', result);
else
% Handle unexpected unit input
fprintf('Unknown units. Please specify "degrees" or "radians".\n');
end
-----------------------------------------------------------------------------------------------------------------------------------------------------
If you find the solution helpful and it resolves your issue, it would be greatly appreciated if you could accept the answer. Also, leaving an upvote and a comment are also wonderful ways to provide feedback.
It's important to note that the advice and code are based on limited information and meant for educational purposes. Users should verify and adapt the code to their specific needs, ensuring compatibility and adherence to ethical standards.
Professional Interests
  • Technical Services and Consulting
  • Embedded Systems | Firmware Developement | Simulations
  • Electrical and Electronics Engineering
Feel free to contact me.
  1 个评论
Spaceman
Spaceman 2024-3-21
Eureka! I especially like how you normalized with the lower function so that it wasn't going to be messed up by capitalizing something on accident and also including the else line to handle unexpected unit input, like someone entering fart instead of degrees. Thank you.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

标签

产品


版本

R2023b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by