#include <stdio.h>
int main()
{
signed int x;
int x1 = 0, x2 = 10, final, loop = 1, y = 10, c;
printf("Enter the value of X.\n");
scanf("%d", &x);
printf("Value Scanned:%d\n", x);
again:
if (loop <= 32)
{
if (x >= x1 && x < x2)
{
final = x - x1;
printf("%d", final);
y = y * 10;
x1 = 0;
x2 = 0;
loop;
goto again;
}
else
{
c = x2 - x1;
if (x1 == x2)
{
x2 = y;
goto again;
}
else if (c == y)
{
x1 = y;
x2 = y;
goto again;
}
else
{
printf("Error in Process");
goto ending;
}
}
}
else
{
printf("0 error, extra long input");
}
ending:
return 0;
}
流程圖:

我是 C 語言的初學者,只知道如何使用 If-else、Switch、Goto 陳述句,具有如何集成基本級別回圈的基本知識。所以請告訴我什么/哪里錯了,而不是告訴我如何使用陣列,因為我不知道它們等等。這是我迄今為止最復雜的代碼。
現在對于編碼的解釋,我將 X1 寫為下限值,將 X2 寫為上限值,同時首先保持它們之間的差 = Y(最初為 10)。同時將 X1 和 X2 的值同時增加 Y(10),我將到達我的 x(input) 所在的交叉點之間。例如- x=568 然后 X1 和 X2 將繼續增加,直到它們達到 X1 = 560 和 X2 = 570,然后他們將執行 Final = X(568) - X1(560) 并列印它。因為它只能發生 32 位長,所以我寫了 loop = 0 并且只處理我的主陳述句,直到回圈小于或等于 32,否則列印“0 錯誤”。然后每次值在我指定的范圍內時,我都會輸入 Y = Y * 10。它應該給我最后一位數字,然后是最后 2 位數字,然后是最后 3 位數字等值。但掃描數值后,一點也不刺激。
uj5u.com熱心網友回復:
在評估您嘗試做的事情時,我重新撰寫了您的代碼,使其在不使用陣列的情況下更加結構化,這似乎是您目前想要避免的事情。然而,現在通常避免使用 goto 陳述句,因為諸如 for 回圈、do/while 回圈和 while 回圈等功能為編碼提供了更好的清晰度。考慮到這一點,以下是提供您想要的功能的代碼片段。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x, x1, x2, y = 10, counter = 0, last_digit;
printf("Please enter a number: ");
scanf("%d", &x);
if (x < 0) /* Just in case a negative integer is entered */
{
x = x * -1;
}
while (1) /* Use a while loop with associated break statements to avoid goto and label statements */
{
x1 = 0;
x2 = 10;
counter = 1;
while (1)
{
if (x >= x1 && x <= x2)
{
last_digit = x - x1;
if (counter == 1)
{
printf("The last digit is: %d\n", last_digit);
}
else
{
printf("The next digit is: %d\n", last_digit);
}
break;
}
x1 = y;
x2 = y;
}
x = x / 10; /* Perform integer division by ten to get to the next digit in the entered number */
if (x == 0) /* Once all digits have been processed the outer while loop can be exited */
{
break;
}
}
return 0;
}
以下是一些關鍵點。
- 如前所述,使用 goto 陳述句的回圈程序由兩個 while 回圈代替;一個while回圈嵌套在另一個while回圈中。
- 利用整數除以十,可以確定和列印每個數字。
- 使用帶有 break 陳述句的嵌套 while 回圈可以實作更緊湊的程式。
使用此代碼片段,以下是來自終端的示例測驗。
@Dev:~/C_Programs/Console/LastDigit/bin/Release$ ./LastDigit
Please enter a number: 479824385
The last digit is: 5
The next digit is: 8
The next digit is: 3
The next digit is: 4
The next digit is: 2
The next digit is: 8
The next digit is: 9
The next digit is: 7
The next digit is: 4
過去,goto 陳述句在編碼中占有一席之地,但今天它幾乎是一種人工制品。
試一試,看看它是否符合您專案的精神。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/524345.html
