c - 尝试使用 scanf() 获取多个变量

标签 c scanf

因此,我决定在我的技能中添加一些编程技能,通常我是一名应用程序支持分析师,具有初级到一般的 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/

相关文章:

c - 注意带有 R 代码的 C 函数名称

c - excel 和打印 - 订单

c - 使用 scanf() 输入时出现问题

c - 使用 sscanf 从文件中读取

C - 使用 scanf 将字符串扫描到数组中

c - 来自文本文件的多维数组

java - 在 O(n) 中查找数组中的所有差异

c - C编程数字和山脉

c - fscanf 不会读取文本文件中的整数值

c - 如何在 C 中打开带有用户输入变量的文件?