【问题标题】:Check whether a point inside or outside a circle (implementation with structs only)检查圆内还是圆外的点(仅使用结构实现)
【发布时间】:2016-03-16 11:54:11
【问题描述】:

首先,我给了一个任务,只用结构来实现它。

我需要检查一个点是否在圆内/外。

输入:点坐标、圆心、半径。

输出:是圆内/外的点。

好吧,我需要使用距离公式d = sqrt( (x_1-x_2)^2 + (y_1 - y_2)^2 ),然后检查它是否更大/更小/等于半径。

我知道逻辑,但我在结构的语法上失败了。你们能帮帮我吗?

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

typedef struct {
    float x;
    float y;
}Point;

typedef struct {
    Point center;
    float radius;
}Circle;

int main()
{
    Point Coordinates;
    Coordinates.x = 0; //Is this initialization necessary?
    Coordinates.y = 0; //Is this initialization necessary?
    Circle insideCircle;
    float distance;
    printf("Please enter the coordinates of your point: ");
    scanf("%f %f", Coordinates.x, Coordinates.y); //after input, throws error.
    printf("Please enter your center coordinate and your radius: "); 
    scanf("%f %f", insideCircle.radius, insideCircle.center.x, insideCircle.center.y);
    printf("%f %f %f %f %f", Coordinates.x, Coordinates.y, insideCircle.radius, insideCircle.center.x, insideCircle.center.y);

//More code for checking if distance > or < or = to radius to be added.
    getch();
}

【问题讨论】:

  • 我宁愿在不必要的时候避免使用 sqrt(),我会将 d² 与 (x1-x2)² + (y1-y2)² 进行比较。如果您需要测试圆内是否有很多点,这会更有效,因为您只需要计算 d² 一次。

标签: c struct scanf


【解决方案1】:

对于scanf(),您需要将变量的地址作为参数传递给提供的转换说明符,例如

scanf("%f %f", &(Coordinates.x), &(Coordinates.y));
               ^                 ^

以及其他用途。

也就是说,检查scanf() 调用的返回值以确保成功至关重要。

【讨论】:

  • 对除字符串先生之外的所有变量。?
  • @IlanAizelmanWS 如果您在之前的评论中指的是 string type (不是文字),那么,是的。
【解决方案2】:
/*i think this piece of code will help you*/

#include <stdio.h>
#include <stdlib.h>

typedef struct {
        float x;
        float y;
}Point;

typedef struct {
        Point center;
        float radius;
}Circle;

int main()
{
        Point Coordinates;
        Coordinates.x = 0;
        Coordinates.y = 0;
        Circle insideCircle;
        float distance;
        printf("Please enter the coordinates of your point: ");
        scanf("%f %f", &(Coordinates.x), &(Coordinates.y) ); //scanf requires &
        printf("Please enter your center coordinate and your radius: ");
        scanf("%f %f %f", &(insideCircle.radius), &(insideCircle.center.x), &(insideCircle.center.y) );//scanf requires &
        printf("%f %f %f %f %f", Coordinates.x, Coordinates.y, insideCircle.radius, insideCircle.center.x, insideCircle.center.y);

        //More code for checking if distance > or < or = to radius to be added.
}

【讨论】:

    猜你喜欢
    • 2016-02-08
    • 2019-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-17
    相关资源
    最近更新 更多