我正在尝试解决:
int total=0, number=0;
float percentage=0.0;
percentage=(number/total)*100;
printf("%.2f", percentage);
如果数字的值为50,总数为100,则我应该得到50.00作为百分比,这正是我想要的。但是我一直得到0.00作为答案,并尝试了许多类型的更改,但它们都没有起作用。整数除法会截断小数部分,所以 (50/100)
的结果为0。你可以将其转换成 float
(最好是 double
),或者先乘以 100.0
(对于 double
精度来说)或者 100.0f
(对于 float
精度来说)。
double percentage;
// ...
percentage = 100.0*number/total;
// percentage = (double)number/total * 100;
或者float percentage;
// ...
percentage = (float)number/total * 100;
// percentage = 100.0f*number/total;
由于浮点数运算不具有结合律,因此100.0*number/total
和 (double)number/total * 100
的结果可能会略有不同(float
同理)。但是在小数点后前两位上的影响极小,因此选择哪种方式可能并不重要。
50/100
将会得到0
。((float)number/total)*100
50.0/100
如果我需要浮点数,我经常会乘以1.0,这比记忆规则更容易。
您正在进行整数算术运算,因此结果是正确的。尝试
percentage=((double)number/total)*100;
顺便提一下,%f
期望的是 double
而不是 float
。纯粹的运气使它在这里被转换了,所以结果很好。但现在在 C 中通常会使用 double
作为浮点类型。
将您的代码更改为:
int total=0, number=0;
float percentage=0.0f;
percentage=((float)number/total)*100f;
printf("%.2f", (double)percentage);
#include <stdio.h>
#include <conio.h>
int main() {
int i,ortust=0,ortalt=0,toplam,dizi[5],sayac;
float ortalama;
for(i=0;i<5;i++)
{
printf("%d. sayiyi giriniz ",i++);
scanf("%d",&dizi[i]);
sayac++;
toplam+=dizi[i];
}
ortalama=(float)(toplam/sayac);
for(i=0;i<5;i++){
if(dizi[i]<ortalama){
ortalt++;
}
else if (dizi[i]>ortalama){
ortust++;
}
}
printf("Ortalama: %2.f\n",ortalama);
printf("Ortalamanin altinda kalan eleman sayisi: \n ",ortalt);
printf("Ortalamanin ustunde kalan eleman sayisi: ",ortust);
getch();
return 0;
}
这应该会给你想要的结果。
double total = 0;
int number = 0;
float percentage = number / total * 100
printf("%.2f",percentage);
这可以给你正确的答案
#include <stdio.h>
int main()
{
float total=100, number=50;
float percentage;
percentage=(number/total)*100;
printf("%0.2f",percentage);
return 0;
}
只需将数值变量从 int 转为 float 即可。
int total=0, number=0;
float percentage=0.0;
percentage=((float)number/total)*100;
printf("%.2f", percentage);
int
部分(=0.5)是0。 - Michaël