How do i fix the output of my code?
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Gabriele Girasole
le 1 Fév 2023
Commenté : Les Beckham
le 1 Fév 2023
Doing some toy problems to get used to Matlab for university.
The following is the program:
a=rand(2,2);
c=1;
cmax=2;
r=1;
rmax=2;
while r<=rmax
while c<=cmax
a(c,r)=round(a(c,r),2);
a(c,r)*100;
c=c+1;
end
r=r+1;
c=1;
end
fprintf ('numero casuale: %i \n' ,a)
I expected the output to be something like:
numero casuale: 40
numero casuale: 80
numero casuale: 24
numero casuale: 12
But it turned out like:
numero casuale: 4.000000e-01
numero casuale: 8.000000e-02
numero casuale: 2.400000e-01
numero casuale: 1.200000e-01
Why did it divide the number by 10 and why did it add so many zeroes. How do i fix the outputs.
0 commentaires
Réponse acceptée
Les Beckham
le 1 Fév 2023
Modifié(e) : Les Beckham
le 1 Fév 2023
a=rand(2,2)
c=1;
cmax=2;
r=1;
rmax=2;
while r<=rmax
while c<=cmax
a(c,r)=round(a(c,r),2);
% a(c,r)*100; << your original code isn't changing a here
a(c,r)=a(c,r)*100;
c=c+1;
end
r=r+1;
c=1;
end
format long g
a-round(a)
fprintf ('numero casuale: %i \n' , a);
fprintf ('numero casuale: %i \n' , round(a)); % round a again to handle floating point precision issues
4 commentaires
Les Beckham
le 1 Fév 2023
You are quite welcome.
Please Accept the answer if it solved your issue. Thanks.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Whos dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!