gpt4 book ai didi

c - 四舍五入为整数

转载 作者:太空宇宙 更新时间:2023-11-04 01:22:22 25 4
gpt4 key购买 nike

该程序是关于获取所有实验室练习的平均值。我想将小数点 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

最佳答案

您的 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

关于c - 四舍五入为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39075352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com