在Matlab中计算百分比

Calculate the percentage in Matlab

我想计算准确率百分比。我有下面的代码。但是它给出了这样的意外输出 "The accuracy is 2.843137e+01x37"。 虽然预期结果是 "The accuracy is 28.43%"

y %Amount of correct data
j %Amount of all data
a = 'The accuracy is %dx%d.';
percent = '%.0f%%';
format short
acc = 100 * double(y/j);
sprintf (a,acc)

如何解决?

如有任何帮助,我们将不胜感激。 谢谢。

试试,

a = 'The accuracy is %f.';
acc = 100 * double(y/j);
sprintf (a,acc)

你几乎得到了你所期望的,只是以正确的方式组合起来。

28.43% 的正确格式说明符是 %.2f%%。这会为您提供小数点后两位数,并在末尾添加 % 符号。您已经在变量 percent 中定义了它,除了 .0 应该是 .2 两个数字,正如您在预期结果中所写的那样。如果仔细观察,您会发现从未使用过 percent

让我们得出结论。将格式说明符更改为以下内容:

a = 'The accuracy is %.2f%%'; 

这就是您需要做的全部。定义 percentformat short 的行可以省略,除非你以后需要它。

关于加倍转换的重要事项:您当前拥有的只是转换结果。如果需要,请在单独yand/orj之前进行强制转换除法。可能您的情况不需要任何转换。


假设 yj 的整个代码是:

y = 28.43137;   %// Amount of correct data
j = 100;        %// Amount of all data

a = 'The accuracy is %.2f%%';
acc = 100 * (y/j);                    %// no cast
% acc = 100 * (double(y)/double(j));  %// with cast
sprintf(a,acc);

输出:

ans =
The accuracy is 28.43%