fprintf from a switch/case?

3 ビュー (過去 30 日間)
Alyssa
Alyssa 2014 年 11 月 27 日
回答済み: Stephen23 2014 年 12 月 1 日
Hello, so I'm doing a problem for an assignment and I was wondering if someone would be able to help me.
The problem is 8.16
So far I have
major = menu('Select an engineering major: ','Civil','Chemical','Computer','Electrical','Mechanical')
switch major
case 1
disp('130');
case 2
disp('130');
case 3
disp('122');
case 4
disp('126.5');
case 5
disp('129');
end
fprintf('The minimum number of credits is: %3.1f \n', major)
But I want the number in the disp() to show in my fprintf, not the case number.

回答 (2 件)

Henrik
Henrik 2014 年 11 月 27 日
This is not the most sophisticated solution, but it works..
switch major
case 1
text_to_print='130';
case 2
text_to_print='130';
case 3
text_to_print='122';
case 4
text_to_print='126.5';
case 5
text_to_print='129';
end
fprintf(['The minimum number of credits is: ' text_to_print '\n'])
  4 件のコメント
Henrik
Henrik 2014 年 11 月 27 日
By the way, switch can also work with text, here's a simple example:
test_string='horse';
switch test_string
case 'horse'
disp('This is a horse')
end
You might be able to do something like
switch major
case 'Civil'
text_to_print='130'
etc. Just a thought.
Or maybe
switch major
case 'Civil'
credits=130;
etc
fprintf(['The minimum number of credits is: ' num2str(credits) '\n'])
per isakson
per isakson 2014 年 11 月 27 日
This line
fprintf(['The minimum number of credits is: ' num2str(credits) '\n'])
may be replaced by
fprintf( 'The minimum number of credits is: %.1f\n' credits )

サインインしてコメントする。


Stephen23
Stephen23 2014 年 12 月 1 日
The following code does much the same as Henrik's answer, but it also:
  • returns the name of the major as well as the credit value.
  • uses the major's name in the switch statement, which makes it clearer which credits belong to what major.
  • uses an fprintf number format that only displays the decimal fraction if it is not zero.
AllMaj = {'Civil','Chemical','Computer','Electrical','Mechanical'};
major = AllMaj{menu('Select an engineering major: ',AllMaj{:})};
switch lower(major)
case 'civil'
pts = 130;
case 'chemical'
pts = 130;
case 'computer'
pts = 122;
case 'electrical'
pts = 126.5;
case 'mechanical'
pts = 129;
end
fprintf('The minimum number of credits for %s Engineering is: %.4g\n',major,pts)
Although the assignment clearly states this prerequisite, using switch is a little heavy handed, and using an array instead would probably be a lot simpler and tidier.

カテゴリ

Help Center および File ExchangeStatistics and Machine Learning Toolbox についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by