How do i fix the output of my code?

조회 수: 1 (최근 30일)
Gabriele Girasole
Gabriele Girasole 2023년 2월 1일
댓글: Les Beckham 2023년 2월 1일
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.

채택된 답변

Les Beckham
Les Beckham 2023년 2월 1일
편집: Les Beckham 2023년 2월 1일
a=rand(2,2)
a = 2×2
0.3808 0.2967 0.9243 0.0692
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)
ans = 2×2
1.0e+00 * 0 0 0 8.88178419700125e-16
fprintf ('numero casuale: %i \n' , a);
numero casuale: 38 numero casuale: 92 numero casuale: 30 numero casuale: 7.000000e+00
fprintf ('numero casuale: %i \n' , round(a)); % round a again to handle floating point precision issues
numero casuale: 38 numero casuale: 92 numero casuale: 30 numero casuale: 7
  댓글 수: 4
Gabriele Girasole
Gabriele Girasole 2023년 2월 1일
thanks, rounding a again before printing, other than the error in line 8, was the issue. Thanks for the insight
Les Beckham
Les Beckham 2023년 2월 1일
You are quite welcome.
Please Accept the answer if it solved your issue. Thanks.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by