If statements and strcmp function

조회 수: 3 (최근 30일)
Spaceman
Spaceman 2024년 3월 21일
댓글: Spaceman 2024년 3월 21일
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