Is there a way to get the switch and case function to be part of the overall formula?

6 次查看(过去 30 天)
I'm trying to create this code that when you choose triangle it will choose n=3 that then will be able to be included in the interior angles sum formula. is that possible? this is for school it's for the question below;
(n−2)(180 degrees)where n is the number of sides.
Write a program that prompts the user to enter one of the following triangle
square
pentagon
hexagon
Use the input to define the value of n via a switch/case structure; then use n to calculate the sum of the interior angles in the figure.
This is the code I have
clear, clc
shapes = input('Choose one', 'Triangle', 'Square', 'Pentagon', 'Hexagon')
switch shapes
case 3
Triangle = 3
n = Triangle
sum = (n-2)*(180)
table = [n; sum]
fprintf('n = %g sum of all interior angles is %g degrees \n', table)
case 4
n = 4
sum = (n-2)*(180)
table = [n; sum]
fprintf('n = %g sum of all interior angles is %g degrees \n', table)
case 5
n = 5
sum = (n-2)*(180)
table = [n; sum]
fprintf('n = %g sum of all interior angles is %g degrees \n', table)
case 6
n = 6
sum = (n-2)*(180)
table = [n; sum]
fprintf('n = %g sum of all interior angles is %g degrees \n', table)
end

采纳的回答

Stephen23
Stephen23 2018-10-15
编辑:Stephen23 2018-10-15
It is a good start, but you should:
  • read the help for each function that you use, then you would learn than input does not accept multiple inputs.
  • you would also learn that the function input does not return an index, as you have used in your code.
  • move the lines sum = ..., table = ... and fprintf... to after the switch (after all, that is the whole point of using that formula!).
  • avoid using the variable names sum and table, which are names of important inbuilt functions.
I simplified your code: made input return a simple char vector, provided the correct input to switch, and moved the calculation to after the switch:
shape = input('Choose one of Triangle, Square, Pentagon, or Hexagon: ','s')
switch lower(shape)
case 'triangle'
n = 3;
case 'square'
n = 4;
case 'pentagon'
n = 5;
case 'hexagon'
n = 6;
end
fprintf('n = %g sum of all interior angles is %g degrees \n',n,(n-2)*(180))
Note that this actually follows the guidelines that you were given: "Use the input to define the value of n via a switch/case structure; then use n to calculate the sum of the interior angles in the figure."

更多回答(0 个)

产品

Community Treasure Hunt

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

Start Hunting!

Translated by