因此,我决定在我的技能中添加一些编程技能,通常我是一名应用程序支持分析师,具有初级到一般的 SQL 编码技能,但在当今的环境下,我知道我需要更好地自动化简单任务。所以我买了c编程类(class)(这不是大学学分,所以问我不是作弊)。到目前为止,一切进展顺利,但我遇到了一个问题,实际上我决定改进给我的挑战,但我似乎无法弄清楚。最初,我被要求创建一个小应用程序,打印出矩形的宽度、高度、周长和面积,并且宽度和高度是硬编码的。这很容易弄清楚。我决定添加一个额外的挑战,让最终用户输入矩形的宽度和高度,但它并没有像我计划的那样工作。我包括我的代码以及编译后的输出。我真的不想得到答案,因为我想自己发现解决方案,但如果有人能给我指出一些文档,我将不胜感激。
代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
double width;
double height;
double perimeter;
double area;
char newLine = '\n';
printf("Please enter the width of your rectangle:");
scanf("%f", &width);
printf("Please enter the height of your rectangle:");
scanf("%f", &height);
perimeter = 2.0 * (height + width);
area = (width * height);
printf("%c",newLine);
printf("The widith of the Rectangle is: %.2f centimeters %c",width, newLine);
printf("The height of the rectangle is: %.2f centimeters %c",height, newLine);
printf("The permimeter of the rectangle is: %.2f centimeters %c",perimeter, newLine);
printf("The area of the rectangle is: %.2f centimeters %c",area, newLine);
printf("%c",newLine);
return 0;
}
输出:
[user@localhost.local]$ ./output/rectangle.a
Please enter the width of your rectangle:15
Please enter the height of your rectangle:12
The widith of the Rectangle is: 0.00 centimeters
The height of the rectangle is: 0.00 centimeters
The permimeter of the rectangle is: 0.00 centimeters
The area of the rectangle is: 0.00 centimeters
最佳答案
您的代码很好,唯一的问题是您使用 %f 而不是 %lf。 %f 用于浮点变量,%lf 用于 double 变量。
修复后程序的输出:
Please enter the width of your rectangle:25
Please enter the height of your rectangle:12
The height of the rectangle is: 12.00 centimeters
The widith of the Rectangle is: 25.00 centimeters
The permimeter of the rectangle is: 74.00 centimeters
The area of the rectangle is: 300.00 centimeters
您可以使用此表来了解如何在 c 中使用每种数据类型: https://www.geeksforgeeks.org/data-types-in-c/
关于c - 尝试使用 scanf() 获取多个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58477127/