gpt4 book ai didi

c - 编写一个 C 程序来计算一个城市的平均季度降雨量?

转载 作者:行者123 更新时间:2023-11-30 17:14:49 24 4
gpt4 key购买 nike

我正在努力编写一个需要为类编写的程序。我需要编写一个程序,从用户那里读取城市名称,然后要求用户输入月份,后跟逗号,然后输入该月的平均降雨量。这是手头的任务:

Write a program that reads data from the user about the quarterly rainfall in a certain city and displays it on the screen. Your program must prompt the user the following information:

  • The name of the city. You may assume it is at most 50 characters.

  • The months and amount of rainfall received for each month. You may assume, for each month, the user will enter both the month and rainfall received values in one line separated by a comma with the month having a length of three characters.

  • The format of the output in terms of field width and precision.

Your program must then calculate the average rainfall and produce output complying with the following specifications:

  • Display the name of the city followed by a blank line.

  • For each monthly rainfall value, display the name of the month left justified in the user specified field width followed by the rainfall for that month displayed right justified formatted using fixed-point notation, with the user specified precision, in a field of 15 spaces wide.

  • Finally follow last month's rainfall with a blank line and then on a separate line display the sentence "Average rainfall: " left justified in the user specified field width followed by the average rainfall right justified in fixed-point notation with the user specified precision and in a field of 15 spaces wide.

现在这是我到目前为止的代码,我正在努力让代码正确,让用户输入自己的逗号,代码编译并运行,但在输入后按回车键后,它不会打印下个月的行第一个月的详细信息,只留下一个空行:

int main () 
{

char cityName[50];
char monthName[3];
char comma;
float aveRain = 0;
int monthCount = 1;
float aveResult = 0;
int fieldWidth;
int outputPrecision;

puts("This program calculates the average quarterly rainfall for a given city.");
printf("Enter the name of the city: ");

scanf("%s" , &cityName[50]);

while( monthCount <= 3 )
{
printf( "Enter the month and average rainfall of month %d: " , monthCount);
scanf( "%s %s %f" , &monthName[3] , &comma , &aveRain);

monthCount = monthCount + 1;
}
}

最佳答案

你的scanf:

  • 您声明 char MonthName[3](仅 2 个字符且终止 null)并读取 &monthName[3] 就在数组末尾:未定义的行为
  • 您尝试使用 char 中的 %s 进行读取:因为 %s 读取至少一个字符并写入终止 null,这里您再次写入 任何有 UB 的地方

你应该:

  • 声明 char MonthName[4] 为终止 null 留出空间
  • 编写cr = scanf("%3s,%f",monthName, &aveRain);以便:
    • 限制输入最多 3 个字符,monthName 中的输入为空
    • 处理逗号
    • 能够控制您是否正确扫描了 2 个字段,或者在输入出现问题时显示错误消息并中止

顺便说一句,前面的 scanf 也很糟糕:您必须在 char 数组中读取,而不是在它之后读取:

scanf("%49s" , cityName); 

关于c - 编写一个 C 程序来计算一个城市的平均季度降雨量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30171892/

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