猜數小遊戲代碼實現

黃名樞 2021-08-15 13:42:54 阅读数:728

本文一共[544]字,预计阅读时长:1分钟~

設計思路:

1、單機,用戶交互

2、格式:使用嵌套循環結構

3、設計語言:Java


Java實現代碼如下:

import java.util.Random;
import java.util.Scanner;
public class Demo{
public static void main (String [] args){
Random r = new Random(); // 實例化一個Random類
int number = r.nextInt(100) + 1;
for (int p = 6 ; p > 0 ; p -- ){
Scanner sc = new Scanner(System.in);
System.out.println("請輸入你猜測的數字:");
int guess = sc.nextInt ();
if (guess > number){
System.out.println("猜大啦!");
}else if (guess < number){
System.out.println("猜小啦!");
}else{
System.out.println("猜對啦!");
break;
}
}
System.out.println("繼續...");
}
}

實例運行效果如下:
image

[========]

C++實現代碼如下:

#include <iostream>
using namespace std;
int main() {
srand((unsigned int)time(NULL));
int n = rand() % 100 + 1;
int k;
int a = 1;
int o = 3;
int d;
int h = 1;
cout << "開始\n";
cout << "請輸入你猜測的數值,你只有3次機會哦!\n";
while (a <= 3)
{
cin >> k;
a++;
if (k < n) {
cout << "猜小啦!\n";
}
else if (k > n) {
cout << "猜大啦!\n";
}
else {
cout << "猜對啦!恭喜您!\n";
break;
}
}
cout << "您的次數用完啦!要繼續猜嗎?\n";
cin >> d;
int g = 1;
if (d > 0) {
while (g <= 3)
{
cin >> k;
if (k < n) {
cout << "猜小啦!\n";
}
else if (k > n) {
cout << "猜大啦!\n";
}
else {
cout << "猜對啦!恭喜您,號!\n";
break;
g++;
}
}
}
else {
cout << "您的次數用完啦!要查看你猜的數嗎?\n";
int m;
cin >> m;
if (m > 0) {
cout << n << endl;
}
else
{
cout << "抱歉,沒有幫上你。\n";
}
}
}

實例運行效果如下:
image

版权声明:本文为[黃名樞]所创,转载请带上原文链接,感谢。 https://gsmany.com/2021/08/20210815134250063u.html