how can i take a variable which store decimal values

7 ビュー (過去 30 日間)
Mukul Khandelwal
Mukul Khandelwal 2015 年 12 月 24 日
コメント済み: John D'Errico 2024 年 1 月 22 日
I am having problem to store decimal value. whenever i am taking greater denominator value it shows only zero . please can any one help me asap
  1 件のコメント
dpb
dpb 2015 年 12 月 24 日
Well, from just the description we don't know precisely what operation you mean by "[I} am taking greater denominator value". Show us code and input.

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

回答 (1 件)

Walter Roberson
Walter Roberson 2015 年 12 月 25 日
If you have variables A, B, that are members of one of the integer classes, such as uint8 or int16, then when you divide A/B the result is defined to be the same as
cast(double(A)/double(B), class(A))
That is, a fraction will be calculated but the result will be made back into the original data type. The process of converting a floating point value to an integer data type is defined to be done by rounding. uint8(159.3) rounds to uint8(159), uint8(159.6) rounds to uint8(160) .
Therefore if you have two integer variables, A/B and B > A, then the result will come out as either 0 or 1 depending on which way the fraction double(A)/double(B) rounds. In particular for A/B with B from A up to and including 2*A will round to 1, and A/B with B > 2*A will round to 0.
If this is a problem then you should either not be using integer class variables or you should be converting the values to double before doing the division, double(A)/double(B) so that the result is not converted back to class(A).
Note: It isn't exactly class(A) that is used in practice but it only makes a difference if you start mixing double and integer class in an operation.
  2 件のコメント
Madhu
Madhu 2024 年 1 月 22 日
移動済み: John D'Errico 2024 年 1 月 22 日
x = 195
fd = 2
y = x./fd
i am getting the value as 98
but i need the value as decimal as 97.2
what can i do/
please anyone help me
John D'Errico
John D'Errico 2024 年 1 月 22 日
your number is an INTEGER. Dividing it by 2 yields another integer.
x = uint8(195)
x = uint8 195
y = x/2
y = uint8 98
class(y)
ans = 'uint8'
You need to convert it to a double FIRST.
z = double(x)/2
z = 97.5000

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

Community Treasure Hunt

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

Start Hunting!

Translated by