gpt4 book ai didi

c - 在 c 中将整数值转换为 float 时出错

转载 作者:行者123 更新时间:2023-11-30 20:34:51 24 4
gpt4 key购买 nike

到目前为止我所拥有的...

<小时/>
        #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 23
#define COLS 78


int main()
{


srand(time(NULL));

int arr[ROWS][COLS];
int sum = 0, counter1 = 0;
int k;
int i;

for (i = 0; i < ROWS; i++)
{
for (k = 0; k < COLS; k++)
{
int j = rand() % 10;

arr[i][k] = j;

printf("%d", arr[i][k]);

sum += arr[i][k];

counter1++;

}
printf("\n");
}

printf("\n");

printf("Average = %f\n", float(sum / counter1)); //Not getting exact decimal

printf("Total numbers = %d\n", counter1);

printf("Sum of all numbers = %d\n", sum);

system("pause");
}
//Guessing the float is not converting as it should
<小时/>

到目前为止的输出....

422620351595919054460397694388416319310552973446498175458548095262118564755749
372438759420195802623062987655437952542263796363224469905714526364539742622586
124057899145417666187341286327350448786294141128615529044980269471365598313616
049149926286317172502475330649055931769733144700851693923585818341846097713250
826490802265735183843662244505193942554706854717207204487697516652123593599812
746605634674496934691593122520210519087830081107377133858638184877543092242563
172193699659454833537193985400677695430588428833192355923118027599256651906912
137220359907772463940456613321876957716810615732837946886780325557272201117024
970243922687865367166306388461501128523059854106020838236007732376011146109340
239699228705450117510917862089719947717228921040726908237444581851160698373585
977683407031265082736130690889715335368791599705700863736964292214408266990418
536416318005520152773513475211623892873091447652802755401011207564392549940648
363921632561931849591970346553864295588487844510186065223062209484132581237554
163065518327032754274153946192470922485557045255627009864269391575284952286729
910378772792028085274954077343530447604501744264499511471498074681140863439500
617676961625579079414287810415495010710519733811672377499905168756599387590803
885768234776892368128405809649999684460473809170548180074483476110165080161362
308905170626655925452893089531708914818032726022522429229062646282887593747734
210270837200571461718554091036728525587376768397741678405601722794577171279012
421649999013761899858408492974830996084297030747093760611147983343593657910519
461743953198670501367758536958306703445033922711724727706025545309033925365602
635580784707723652610577238350330553362131582484629421787969994692199573628406
521293251392156351047950677006976709658442231650692040031419198232429972214834

Average = 4.000000

Total numbers = 1794

Sum of all numbers = 8054

Press any key to continue . . .

最佳答案

您可以通过放置“.2f”将数字格式化为小数点后两位:

printf("Average = %.2f\n", float(sum) / float(counter1));

关于c - 在 c 中将整数值转换为 float 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41082852/

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