- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在努力编写一个需要为类编写的程序。我需要编写一个程序,从用户那里读取城市名称,然后要求用户输入月份,后跟逗号,然后输入该月的平均降雨量。这是手头的任务:
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]
就在数组末尾:未定义的行为%s
进行读取:因为 %s
读取至少一个字符并写入终止 null,这里您再次写入 任何有 UB 的地方你应该:
char MonthName[4]
为终止 null 留出空间cr = scanf("%3s,%f",monthName, &aveRain);
以便:
monthName
中的输入为空顺便说一句,前面的 scanf 也很糟糕:您必须在 char 数组中读取,而不是在它之后读取:
scanf("%49s" , cityName);
关于c - 编写一个 C 程序来计算一个城市的平均季度降雨量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30171892/
我是一名优秀的程序员,十分优秀!