Randomly giving "ans" value but i dont want that

1 visualización (últimos 30 días)
Melih Eren
Melih Eren el 26 de Abr. de 2024
Comentada: Adam Danz el 26 de Abr. de 2024
We made a basic function code but for some reason it's giving "ans" value as sayi1+sayi2(toplam)
How can i prevent the creation of the "ans" ?
Heres the code:
function [toplama, cikarma, carpma, bolme, ortalama] = hesap_makinesi(sayi1,sayi2)
toplama=sayi1+sayi2
cikarma=sayi1-sayi2
carpma=sayi1*sayi2
bolme=sayi1/sayi2
ortalama=(sayi1+sayi2)/2
end
Output:
>> hesap_makinesi(6,2)
toplama =
8
cikarma =
4
carpma =
12
bolme =
3
ortalama =
4
ans =
8

Respuestas (1)

Dyuman Joshi
Dyuman Joshi el 26 de Abr. de 2024
Editada: Dyuman Joshi el 26 de Abr. de 2024
"How can i prevent the creation of the "ans" ?"
When calling a function with multiple outputs without specifying the outputs, only the 1st output is returned. And as you have not defined which variable to store the (first) output in, MATLAB uses "ans" as the variable name (by default).
You can prevent that by suppressing the call via a semi-colon -
hesap_makinesi(6,2);
toplama = 8
cikarma = 4
carpma = 12
bolme = 3
ortalama = 4
function [toplama, cikarma, carpma, bolme, ortalama] = hesap_makinesi(sayi1,sayi2)
toplama=sayi1+sayi2
cikarma=sayi1-sayi2
carpma=sayi1*sayi2
bolme=sayi1/sayi2
ortalama=(sayi1+sayi2)/2
end
  1 comentario
Adam Danz
Adam Danz el 26 de Abr. de 2024
Alternatively, you can return ouputs only when they are requested.
Use nargout to determine how many outputs were requested.
function [toplama, cikarma, carpma, bolme, ortalama] = hesap_makinesi(sayi1,sayi2)
if nargout > 0
toplama=sayi1+sayi2;
end
if nargout > 1
cikarma=sayi1-sayi2;
end
if nargout > 2
carpma=sayi1*sayi2;
end
if nargout > 3
bolme=sayi1/sayi2;
end
if nargout > 4
ortalama=(sayi1+sayi2)/2;
end
end
Demos
hesap_makinesi(6,2)
toplama = hesap_makinesi(6,2)
toplama = 8
[toplama,cikarma] = hesap_makinesi(6,2)
toplama = 8
cikarma = 4
[~, ~, carpma] = hesap_makinesi(6,2)
carpma = 12
[~, ~, carpma, ~, ortalama] = hesap_makinesi(6,2)
carpma = 12
ortalama = 4

Iniciar sesión para comentar.

Categorías

Más información sobre Application Deployment en Help Center y File Exchange.

Productos


Versión

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by