【问题标题】:C - Inputting whilst LoopingC - 循环输入
【发布时间】:2012-07-29 09:51:43
【问题描述】:

我正在尝试学习 C,并且我编写了一个小程序来计算各种形状的面积。以下是源代码:

#include "stdafx.h"

struct entry
{
    float x;
    float y;
};

void square()
{
    printf("\nPlease enter the size of one of the square's sides\n");

    struct entry sq;
    scanf_s("%f\n", &sq.x);

    printf("\nThe area of the square is %.2f\n\n", sq.x * sq.x);
}

void rectangle()
{
    printf("\nPlease enter the length and breadth of the rectangle\n");

    struct entry rec;
    scanf_s("%f\n", &rec.x);
    scanf_s("%f\n", &rec.y);

    printf("\nThe area of the rectangle is %.2f\n\n", rec.x * rec.y);
}

void triangle()
{
    printf("\nPlease enter the width and height of the triangle\n");

    struct entry tri;
    scanf_s("Width: %f\n", &tri.x);
    scanf_s("Height: %f\n", &tri.y);

    printf("\nThe area of the triangle is %.2f\n\n", (tri.x * tri.y)/2);
}

void circle()
{
    printf("\nPlease enter the radius of the circle\n");

    struct entry circ;
    scanf_s("%f\n", &circ.x);

    printf("\nThe area of the circle is %.2f\n\n", 3.14 * circ.x * circ.x);
}


void main()
{
    int input = 0;

    do
    {
        printf("---Area of a Shape---\n\n");
        printf("1. Square\n");
        printf("2. Rectangle\n");
        printf("3. Triangle\n");
        printf("4. Circle\n");
        printf("5. Exit\n");
        printf("\n\n");

        printf("Please make a choice\n");
        scanf_s("%d", &input);

        switch(input)
        {
            case 1: square();
                    break;

            case 2: rectangle();
                    break;

            case 3: triangle();
                    break;

            case 4: circle();
                    break;

            case 5: printf("\n\nThank you for using this program!  Press enter to exit!\n");
                    break;

            default: printf("\nInvalid choice!\n\n");
                    break;
        }       
    }
    while(input != 5);

    getchar();
    getchar();
}

该程序唯一的问题是,在输入边的大小以计算面积后,它会等待我输入另一个数字(做出选择),然后再显示答案。我不知道问题出在哪里。我认为在转移到另一个函数之前,C 会确保它执行手头的整个函数。你能帮我解决这个问题吗?谢谢。

【问题讨论】:

    标签: c loops area


    【解决方案1】:

    在您的 scanf 格式中,

    scanf_s("%f\n", &rec.x);
    

    '\n' 不代表文字 '\n',而是代表任意的空白字符序列。因此scanf_s 调用不会结束,直到您在数字(和空格)之后输入一个非空白字符[输入可能不会发送到您的程序,直到您在此之后键入换行符]。只需从格式中删除 '\n'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-10
      • 2015-06-07
      • 2019-03-05
      • 2017-04-20
      相关资源
      最近更新 更多