首先,輸入正方形頂點的坐標。并且每個坐標不能超過1000。其次,輸入坐標的當前位置。坐標的位置不能超過正方形。我想找到從坐標到正方形的最小距離。這是我想做的內容。所以我做了下面的代碼。
#define _CRT_SECURE_NO_WARNINGS
#include<stdlib.h>
#include<stdio.h>
void min_comparison(int a, int b, int c, int d);
typedef struct coordinate {
unsigned int x; unsigned int y;
unsigned int w; unsigned int h;
}coord;
int main()
{
int nomi1;
int nomi2;
coord cod;
presentcoord:
printf("enter the coordinates of the vertex of the square: ");
scanf("%d %d", &cod.x, &cod.y);
if (cod.x >= 1001 || cod.y >= 1001)
{
printf("The vertex coordinates cannot exceed 1000.\n");
goto presentcoord;
}
presentloca:
printf("enter the current location of the coordinates: ");
scanf("%d %d", &cod.w, &cod.h);
if (cod.w >= cod.x || cod.h >= cod.y)
{
printf("location of the coordinates can't excced %d, %d.\n",cod.x-1,cod.y-1);
goto presentloca;
}
printf("\n");
nomi1 = cod.x - cod.w;
nomi2 = cod.y - cod.h;
min_comparison(cod.x, cod.y, nomi1, nomi2);
}
void min_comparison(int a,int b,int c,int d)
{
int min; int min1; int result;
if (a > c)
min = c;
else min = a;
if (b > d)
min1 = d;
else min1 = b;
if (min > min1)
result = min1;
else result = min;
printf("minimum distance from coordinates to square is %d.\n", result);
return 0;
}
我在谷歌上查了一下,它說“goto”是一個糟糕的代碼。
所以我想知道如何替換代碼的“goto”部分。
而且英語不是我的第一語言。所以也要指出錯誤的英文表達。
如果你讓我知道,我將不勝感激。
uj5u.com熱心網友回復:
您可以輕松地轉換您的代碼。這部分
presentcoord:
printf("enter the coordinates of the vertex of the square: ");
scanf("%d %d", &cod.x, &cod.y);
if (cod.x >= 1001 || cod.y >= 1001)
{
printf("The vertex coordinates cannot exceed 1000.\n");
goto presentcoord;
}
可以簡化為這種通用形式:
label:
<do something>
<Check if we are done>
<If not, goto label>
這可以轉換為通用回圈:
bool done = false;
do
{
<do something>
<check if we are done>
<if yes: done=true;>
<else: Print message>
}while (!done);
在你的情況下,這將是
bool done = false;
do
{
printf("enter the coordinates of the vertex of the square: ");
scanf("%d %d", &cod.x, &cod.y);
if (cod.x >= 1001 || cod.y >= 1001)
{
printf("The vertex coordinates cannot exceed 1000.\n");
}
else
{
done = true;
}
} while (!done);
uj5u.com熱心網友回復:
do-whileGerhardh 提出的版本很好。另一個更緊湊的替代方案是:
while(1)
{
printf("enter the coordinates of the vertex of the square: ");
scanf("%d %d", &cod.x, &cod.y);
if (cod.x <= 1000 && cod.y <= 1000)
break; // stop if input ok
printf("The vertex coordinates cannot exceed 1000.\n");
}
uj5u.com熱心網友回復:
這應該有效,(未經測驗)。continue將像goto回傳到 while 回圈的開頭一樣,并且break將像goto到 while 回圈的結尾一樣。
while(1){
printf("enter the coordinates of the vertex of the square: ");
scanf("%d %d", &cod.x, &cod.y);
if (cod.x >= 1001 || cod.y >= 1001)
{
printf("The vertex coordinates cannot exceed 1000.\n");
continue;
}
break;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/439324.html
上一篇:C-如何在宏中使用多個函式?
下一篇:使用JPA檢索特定的多值關聯列
