C语言goto语句可以怎么替换?【具体代码看补充】

Python016

C语言goto语句可以怎么替换?【具体代码看补充】,第1张

#include "stdio.h"

#include"process.h"

#include <conio.h>

#define MAX  100

int a = 0, price[MAX]

add()

{

 

    int p = 0

   printf("请输入价格:\n")

    do

    {

        p++

       scanf("%d", &price[p - 1])

        if(p>= MAX)

        {

           printf("数据已满!")

           break

        }

    }

   while(price[p - 1] >= 0)

    price[p - 1]= 0

    return 0

 

}

print()

{

    int i = 0, j= 0

    while(i<= MAX)

    {

        if(price[i] == 0)

        {

            printf("价格已输入完毕")

            break

        }

        printf("%d,%d\n", price[i], price[i + 1])

        i += 2

        j++

        if(j>= 10)

        {

            j =0

            printf("\n")

            continue//will goto while

        }

    }

    getch()

    system("cls")

    return 0

}

FIND()

{

    int m =price[0], n

    for(n = 1 n< MAX n++)

    {

        if(price[n] > m)   m =price[n]

        if(price[n] == 0)  break

    }

    printf("max=%d", m)

    return 0

}

void main()

{

//loop:

    while(a<4)

    {

        printf("1、录入价格\n")

        printf("2、输出价格\n")

        printf("3、查询价格\n")

        printf("4、退出\n")

        scanf("%d", &a)

        switch(a)

        {

        case 1:

            add()

            system("cls")

            break

        case 2:

            print()

            system("cls")

            break

        case 3:

            FIND()

            getch()

            system("cls")

            break

        case 4:

            printf("谢谢使用该系统!\n")

            break

        }

    }

}

goto语句也称为无条件转移语句,其一般格式如下: goto 语句标号; 其中语句标号是按标识符规定书写的符号, 放在某一语句行的前面,标号后加冒号(:)。语句标号起标识语句的作用,与goto 语句配合使用。

如: label: i++

loop: while(x<7)

goto loop

C语言不限制程序中使用标号的次数,但各标号不得重名。goto语句的语义是改变程序流向, 转去执行语句标号所标识的语句。

goto语句通常与条件语句配合使用。可用来实现条件转移, 构成循环,跳出循环体等功能。

扩展资料:

go to语句使用原则:

1、使用goto语句只能goto到同一函数内,而不能从一个函数里goto到另外一个函数里。

2、使用goto语句在同一函数内进行goto时,goto的起点应是函数内一段小功能的结束处,goto的目的label处应是函数内另外一段小功能的开始处。

3、不能从一段复杂的执行状态中的位置goto到另外一个位置,比如,从多重嵌套的循环判断中跳出去就是不允许的。

4、应该避免向两个方向跳转。这样最容易导致"面条代码"。

参考资料:百度百科-goto语句

可以使程序跳转到标记位置,可以和if语句构成循环,但是对于goto语句的使用争议很大,它能使程序很轻松的跳出多个嵌套循环,但是会破坏程序的模块化,使程序的可读性变差,项目越大这个缺点越明显,所以个人观点不建议使用,了解就可以了,goto语句的一些用处while和do

while循环可以代替。

用法举例:

#include

<stdio.h>

#include

<stdlib.h>

int

main()

{

char

input

loop:

printf("Hello,

world!\n")

printf("Repeat?(y/n)")

scanf("%c",

&input)

if

(input

==

'y')

{

goto

loop

}

system("pause")

return

0

}