用c语言写出田忌赛马的流程图和程序

用c语言写出田忌赛马的流程图和程序,第1张

根据流程图,我写了一个完整的程序给你参考。

源代码如下(vc++6.0下编译通过):

#include <stdio.h>

int main(void)

{

int x=0,max=0,min=0,i=0,s=0

printf("please input a number(x): \n")

scanf("%d", &x)

max = x

min = x

#include <iostream>

#include <string>

#include <vector>

#include <algorithm>

#include <time.h>

const std::string GetGongziHorse(std::vector<std::string>& horse)

{

int size = horse.size()

int choose = rand()%size

std::string horseChoosed = horse[choose]

std::vector<std::string>::iterator it 

= find(horse.begin(), horse.end(), horseChoosed)

horse.erase(it)

return horseChoosed

}

const std::string GetTianjiHorse(const std::string& horseChoosed)

{

if (strcmp(horseChoosed.c_str(), "千里马") == 0)

return "劣马"

else if (strcmp(horseChoosed.c_str(), "好马") == 0)

return "千里马"

else

return "好马"

}

int main(void)

{

srand(time(NULL))

std::string strHorse[] = {"千里马", "好马", "劣马"}

std::vector<std::string> horseGongzi

horseGongzi.insert(horseGongzi.end(), strHorse, strHorse + 3)

int i = 1

while(horseGongzi.size())

{

std::string horseChoosed = GetGongziHorse(horseGongzi)

std::cout << "第" << i << "场" << std::endl

std::cout << "虚空公子派出了:" << horseChoosed << std::endl

std::cout << "田忌派出了:" 

                  <<  GetTianjiHorse(horseChoosed) << std::endl

i++

std::cout << std::endl

}

std::cout << "田忌无耻的赢了" << std::endl

getchar()

return 0 

}

我调试了一下,需要把两层for循环里面if语句里面的执行体

i++j++

continue

把这两句改成一句:

break

因为比如a[3]>b[6],那么接下来我们只需要从i=4开始判断就行了,跳出当前j循环,就是从i=3进入到i=4。

而如果像原来那样都加1,则当(j+1)+1>=n时很有可能跳到(i+1)+1=5上去。并且就算跳到i=4上,那么j也不是从0开始了,而是从半路的6+1+1=8开始了。

我的程序,题目给的五个样例都通过了:

#include <stdio.h>

#include <stdlib.h>

#define maxn 1000

int main()

{

int n, num

int i, j, t

int mine[maxn], his[maxn]

do {

num=0

scanf("%d",&n)

if (n>=1 &&n<=1000) {

for (i=0i<ni++) scanf("%d", &mine[i])

for (i=0i<ni++) scanf("%d", &his[i])

//Sort mine[]={5,4,6,1,9} to {1,4,5,6,9}.

for (i=0i<n-1i++)

for (j=i+1j<nj++)

if (mine[i]>mine[j]) {

t=mine[i]

mine[i]=mine[j]

mine[j]=t

}

for (i=0i<ni++)

for (j=0j<nj++)

if (mine[i]>his[j] &&mine[i]!=0 &&his[j]!=0) {

num++

printf("%d %d---%d.......",mine[i],his[j],num)

mine[i]=his[j]=0

break

}

printf("%d and %d \n", num, n/2+1)

if (num>=n/2+1)

printf("YES\n")

else

printf("NO\n")

}

} while(n!=0)

system("pause")

return 0

}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/yw/11833045.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-19
下一篇 2023-05-19

发表评论

登录后才能评论

评论列表(0条)

保存