gpt4 book ai didi

c - 函数中未初始化的变量

转载 作者:行者123 更新时间:2023-11-30 19:15:24 25 4
gpt4 key购买 nike

我的任务是编写一个接受三个输入并返回三个值的程序。整个程序在这里:

#include <stdio.h>


int findPercent(int percent)
{
int p = percent / 100;
return p;
}

double convertSquareYards(int a)
{
double sy = a * 4840;
return sy;
}

double convertCubicYards(double sy, double i, int p)
{
double cy = (sy * p) * (i / 36);
return cy;
}

double convertGallons(double cy)
{
double g = cy / 201.974026;
return g;
}

double convertPounds(double g)
{
double lb = g / 8.3430;
return lb;
}

double convertTonnes(double lb)
{
double t = lb / 2000;
return t;
}

double convertCubicFeet(double cy)
{
double cf = cy * 27;
return cf;
}

double findHeight(double cf)
{
double h = ((cf / (360 * 160)) / 5280);
return h;
}

int main(void)
{

double g, t, h, lb, i, cy, a, percent, cf;

printf("What is the size of the county in acres? ");
scanf("%lf", &a);

printf("How much rainfall was recieved, in inches? ");
scanf("%lf", &i);

printf("What percent of the county recieved rainfall? ");
scanf("%lf", &percent);


g = convertGallons(cy);
t = convertTonnes(lb);
h = findHeight(cf);

printf("%lf gallons fell in the county.\n", g);
printf("The rainfall weighed %lf tonnes.\n", t);
printf("The height of the football field is %lf miles.\n", h);

return 0;
}

当我尝试编译该程序时,出现以下错误:

project.c:67:3: warning: ‘cy’ is used uninitialized in this function [-Wuninitialized]
g = convertGallons(cy);
^
project.c:68:3: warning: ‘lb’ is used uninitialized in this function [-Wuninitialized]
t = convertTonnes(lb);
^
project.c:69:3: warning: ‘cf’ is used uninitialized in this function [-Wuninitialized]
h = findHeight(cf);
^

我确信这个程序有很多问题(这是我的第一个真正的程序),如果您愿意,我很乐意听到任何其他意见。先感谢您。

最佳答案

在这种情况下,警告非常具有描述性;您在初始化变量之前使用变量,这在 C 中不是一个好主意,例如

 g = convertGallons(cy);

cy 在上面使用之前没有初始化。使用

double cy = 0; // Or some other initial value

在声明期间(其他变量相同)。读取未初始化变量的值(这就是当该变量传递给函数时发生的情况 - 生成了它的副本,因此在某种程度上正在读取)是未定义的行为,并且编译器似乎是提示这一点。

关于c - 函数中未初始化的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32645150/

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