作业帮 > 综合 > 作业

下面两个程序,关于float和double.为什么float的那个程序在后面要有(float),但double这个却不用

来源:学生作业帮 编辑:灵鹊做题网作业帮 分类:综合作业 时间:2024/04/30 02:39:17
下面两个程序,关于float和double.为什么float的那个程序在后面要有(float),但double这个却不用加(double
#include
int main(void)
{
int counter,grade,total;
float average;
total = 0;
counter =0;
printf("Enter grade,-1 to End;");
scanf("%d",&grade);
while( grade!=-1 ) {
total = total + grade;
counter =counter + 1;
printf("Enter grade,-1 to End:");
scanf("%d",&grade);
}
if(counter = 0){
average =(float) total/counter;
printf("class average is %.2f\n",average);
}
else{
printf("No grades weres entered\n");
}
return 0;
}
#include
#include
int main(void)
{
double amount,principal = 1000.0,rate=.05;
int year;
printf("%4s%21s\n","Year","Amount on deposit");
for(year = 1;year
下面两个程序,关于float和double.为什么float的那个程序在后面要有(float),但double这个却不用
在第一个程序中,counter,total都是整型,他们两个相除的结果也是整型,但是很显然,你并不希望5/2=2,而是希望得到2.5;所以需要对average进行强制类型转换,在前面加上(float );
在第二个程序中,由于数据都是双精度类型浮点数,不需要进行强制类型转换,所以不需要加(double)!