该计划旨在获得所有实验室锻炼的平均值。我想将我的小数7.7778舍入为整数。我尝试了ceilf和roundf()它不能正常工作,我的代码有什么问题吗?任何帮助将不胜感激谢谢!
我的代码
#include<stdio.h>
#include<conio.h>
#include <math.h>
int main()
{
int numberof_laboratory,lab_exercises,total_numberof_laboratory,average,roundoff;
char answer;
do
{
printf("\nEnter number of laboratory:");
scanf("%d",&numberof_laboratory);
for(int i=1;i<=numberof_laboratory;++i)
{
printf("\nEnter laboratory exercise %d:",i);
scanf("%d",&lab_exercises);
total_numberof_laboratory += lab_exercises;
average = total_numberof_laboratory / 3;
roundoff = ceilf(average * 100) / 100;
}
printf("The average laboratory exercise grade is %d",roundoff);
printf("\nDo you want to continue(Y/N)?");
scanf(" %c", &answer);
}
while(answer != 'N' && answer != 'n');
printf("Goodbye!");
}
实施例
输入实验室数量:3
实验练习1:10
实验练习2:7
实验练习1:6
平均实验室运动等级为:7 //应为8
答案 0 :(得分:3)
您的roundoff = ceilf(average * 100) / 100;
错了
average
被声明为int
。
您应该按如下方式声明:
float average;
...
average = total_numberof_laboratory / 3.0f; // thanks to Ed Heal
roundoff = roundf(average);
您似乎想要以下内容:
#include <stdio.h>
#include <math.h>
int main()
{
int numberof_laboratory, lab_exercises, total_numberof_laboratory, roundoff;
float average; /* see here */
char answer;
do
{
printf("\nEnter number of laboratory:");
scanf("%d",&numberof_laboratory);
total_numberof_laboratory = 0; /* see here important */
for(int i=1;i<=numberof_laboratory;++i)
{
printf("\nEnter laboratory exercise %d:",i);
scanf("%d",&lab_exercises);
total_numberof_laboratory += lab_exercises;
}
average = total_numberof_laboratory / (float)numberof_laboratory; /* see here */
roundoff = roundf(average); /* see here */
printf("The average laboratory exercise grade is %d",roundoff);
printf("\nDo you want to continue(Y/N)?");
scanf(" %c", &answer);
}
while(answer != 'N' && answer != 'n');
printf("Goodbye!");
}
在gcc
中编译为
gcc -o main main.c -lm -Wall -pedantic
答案 1 :(得分:1)
您应该使用以下代码来查找所需的平均值 -
#include<stdio.h>
#include<conio.h>
#include <math.h>
int main()
{
int i,numberof_laboratory, lab_exercises, total_numberof_laboratory=0,roundoff;
float average;
char answer;
do
{
printf("\nEnter number of laboratory:");
scanf("%d",&numberof_laboratory);
for(i=1;i<=numberof_laboratory;++i)
{
printf("\nEnter laboratory exercise %d:",i);
scanf("%d",&lab_exercises);
total_numberof_laboratory += lab_exercises;
}
average = (float)total_numberof_laboratory /numberof_laboratory ;
roundoff = ceil(average);
printf("The average laboratory exercise grade is %d",roundoff);
printf("\nDo you want to continue(Y/N)?");
scanf(" %c", &answer);
}
while(answer != 'N' && answer != 'n');
printf("Goodbye!");
}
您应该清楚地了解并注意所做的更改。
total_numberof_laboratory
计算lab_exercises
的总和
那么它必须用0值average
应在评估总和后计算average
应声明为float average = (float)total_numberof_laboratory /numberof_laboratory ;
计算,average = (float)total_numberof_laboratory / 3 ;
无法计算ceil
只需ceilf
乐意提供帮助; - ]