필터 지우기
필터 지우기

how to input a string into a function?

조회 수: 30 (최근 30일)
Swapnil srivastava
Swapnil srivastava 2017년 4월 27일
댓글: Stephen23 2017년 4월 27일
my function is
function [Title,Author,Number_of_pages]=disp_book(Tit,Aut,Nu_of_pg)
fprintf('Title: %s',Tit)
fprintf('Author: %s',Aut)
fprintf('Number of pages: %d',Nu_of_pg)
end
but if i prompt disp_book(name,author,33) the computer doesnt take the string. How do I make it work?
  댓글 수: 3
Swapnil srivastava
Swapnil srivastava 2017년 4월 27일

So for example if i prompt disp_book(Harry Potter, JK Rowling, 300) my output should be Title: Harry potter Author: JK Rowling Number of pages: 300 but when i actually do that it says function or variable Harry Potter undefined

Stephen23
Stephen23 2017년 4월 27일
@Swapnil srivastava: your comment shos that you forgot to use quotation marks to define the string. See my answer for the correct way to call this function with string inputs.

댓글을 달려면 로그인하십시오.

답변 (1개)

Stephen23
Stephen23 2017년 4월 27일
It is not totally clear what you are trying to achieve with that function, as you are both printing the output to the command window using fprintf and you also have defined some function outputs (but you never allocated to these outputs). Judging by the function name the outputs are not required, so I removed the superfluous outputs and added newline characters to the fprintf format strings:
function disp_book(Tit,Aut,Nu_of_pg)
fprintf('Title: %s\n',Tit)
fprintf('Author: %s\n',Aut)
fprintf('Number of pages: %d\n',Nu_of_pg)
end
And tested:
>> disp_book('Dr Seuss','The Cat in the Hat',64)
Title: Dr Seuss
Author: The Cat in the Hat
Number of pages: 64
>>

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by