(数学实验)Matlab实现猜数小游戏(增加了错误输入的判断)

刚开始做的时候不知道matlab没有自减运算,在网上查了很久资料,都没发现有对猜数游戏加错误输入判断的,经过多次试错,我弄出来了有判断的程序,在这里分享一下。

文章目录


前言

Matlab写猜数程序主要考察学习者考虑问题的严密性和多分支结构,这个题目增加了错误输入的判断,也就是输入不在范围内的数,不计一次。要注意Matlab没有自增、自减操作,所以在循环时要考虑是选择for循环还是while循环。


一、问题描述

首先由计算机产生[1,100]之间的随机整数,然后由用户猜测所产生的随机数。

根据用户猜测的情况给出不同提示,如猜测的数大于产生的数,则显示“High”,小于则显示 “Low”,等于则显示 “You won”,同时退出游戏。用户最多可以猜7次。如输入非[1,100]之间的数则要求用户重输,不计为一次。猜完7次还没猜对的,请提示“次数用尽”。

二、解题思路

1.for循环

代码如下(示例):

magic = randperm(100,1);%电脑随机产生[1-100]的整数
num=1; %用户猜的次数,初始化为1
sign = 1; %定义一个标识变量,后续当猜对时更改它的值,跳出循环
for i = 1:7
   guess = input('Please input a number: '); 
   if guess < magic  %猜得太小
      disp('Low') ;
   elseif guess > magic  %猜得太大
      disp('High');
   elseif guess == magic  %猜对了
       disp('You won!');
       sign = 0;  %改变sign变量的值,并跳出循环
       break;
   end
end
if sign == 1  %猜了7次还没猜对,结束游戏
   disp('次数用尽!'); 
end
 

目前题目完成90%,还有错误输入未完成,(这里大家可以尝试一下把错误输入的判断加进去,但执行的时候并不能实现。)因为在for循环里面更改变量的值不能传到大的循环范围去,经过多次试错,我想到了可以改用while循环进行操作。

2.while循环

代码如下(示例):

magic = randperm(100,1);%电脑随机产生[1-100]的整数
num=1; %用户猜的次数,初始化为1
sign = 1; %定义一个标识变量,后续当猜对时更改它的值,跳出循环
while num <= 7
   guess = input('Please input a number: '); 
   if guess < 1 || guess > 100   %处理错误输入数据,输入不在范围内的数,num值不增加
        disp('错误输入,请重猜一次!');
        continue;
   end    %注意这里要让if条件终止,否则错误输入的数也会被判断是否猜对
   if guess < magic  %猜得太小
      disp('Low') ;
      num = num + 1;
   elseif guess > magic  %猜得太大
      disp('High');
      num = num + 1;
   elseif guess == magic  %猜对了
       disp('You won!');
       sign = 0;  %改变sign变量的值,并跳出循环
       break;
   end
end
if sign == 1  %猜了7次还没猜对,结束游戏
   disp('次数用尽!'); 
end
 

这里在while循环里面添加了一个if条件语句,实现了错误输入的判断。

 

3.C语言实现

代码如下(示例):

#include<stdio.h>
int main()
{
    int magic=rand()%100+1;
    int guess;
    int num;
    int sign = 1;
    for(num=1;num<8;num++)
    {
         printf("Please input a number:");
        scanf("%d",&guess);
        if(guess < 1 || guess > 100)
        {
            printf("错误输入,请重猜一个数:\n");
            num--;
            continue;
        }
        if(guess > magic)
         {
             printf("High\n");
            continue;
         }
        if(guess < magic)
         {
                printf("Low\n");
            continue;
         }
        if(guess == magic)
            printf("You won\n");
            sign = 0;
            break;
    }
       if(sign == 1)
          printf("次数用尽");
    return 0;
}

 

 

 C语言中用自减就能实现,很简单。

总结

以上就是猜数游戏解题思路,虽然花了很长时间才解决错误输入判断的写法,但过程中我也学到了很多,也希望能解决其他有此问题的人的疑问。学如逆水行舟,不进则退,我会多敲代码,熟练技艺。

function varargout = caishuzi(varargin) %CAISHUZI M-file for caishuzi.fig % CAISHUZI, by itself, creates a new CAISHUZI or raises the existing % singleton*. % % H = CAISHUZI returns the handle to a new CAISHUZI or the handle to % the existing singleton*. % % CAISHUZI('Property','Value',...) creates a new CAISHUZI using the % given property value pairs. Unrecognized properties are passed via % varargin to caishuzi_OpeningFcn. This calling syntax produces a % warning when there is an existing singleton*. % % CAISHUZI('CALLBACK') and CAISHUZI('CALLBACK',hObject,...) call the % local function named CALLBACK in CAISHUZI.M with the given input % arguments. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help caishuzi % Last Modified by GUIDE v2.5 08-Mar-2008 22:02:40 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @caishuzi_OpeningFcn, ... 'gui_OutputFcn', @caishuzi_OutputFcn, ... 'gui_LayoutFcn', [], ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before caishuzi is made visible. function caishuzi_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin unrecognized PropertyName/PropertyValue pairs from the % command line (see VARARGIN) % Choose default command line output for caishuzi handles.output = hObject; handles.source = rand4; %生成一个随机的四位 handles.pc = 0; %用来保存按‘ok’键的次,但不成功 % Update handles structure guidata(hObject, handles); % UIWAIT makes caishuzi wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = caishuzi_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; function edit_input_Callback(hObject, eventdata, handles) % hObject handle to edit_input (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit_input as text % str2double(get(hObject,'String')) returns contents of edit_input as a double handles.instr = str2double(get(hObject,'String')); %从编辑框取输入值 guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function edit_input_CreateFcn(hObject, eventdata, handles) % hObject handle to edit_input (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in pushbutton_clo. function pushbutton_clo_Callback(hObject, eventdata, handles) % hObject handle to pushbutton_clo (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) delete(handles.figure1) %关闭界面 % --- Executes on selection change in popupmenu. function popupmenu_Callback(hObject, eventdata, handles) % hObject handle to popupmenu (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = get(hObject,'String') returns popupmenu contents as cell array % contents{get(hObject,'Value')} returns selected item from popupmenu handles.bushu = get(hObject,'value'); %获得指定步限制,还未完成该功能 % --- Executes during object creation, after setting all properties. function popupmenu_CreateFcn(hObject, eventdata, handles) % hObject handle to popupmenu (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in pushbutton_ok. function pushbutton_ok_Callback(hObject, eventdata, handles) % hObject handle to pushbutton_ok (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) A = handles.source; %A为生成的随机4位 instr = handles.instr; %输入的4位 handles.pc = handles.pc + 1; %按键次 b = 0; %将输入的4位拆开,组成矩阵B for i=1:4 B(5-i) = mod(instr,10); for j=1:4 if isequal(B(5-i),A(j)) %判断B与A是否有相同元素,并将其个存入b b=b+1; end end instr = fix(instr/10); end %判断输入是否合法 f=0; for i=1:4 C(1:4)=B(i); if sum(C==B)>=2 set(handles.text_rez, 'string','请重新输入4位不重复!'); f=1; break end end if f==0 %输入合法 a=sum(A==B); %A与B的元素及其位置均相同的元素个 b = b - a; %A与B的元素相同但位置不相同的元素个 set(handles.text_rez, 'string',['第',num2str(handles.pc),'步: ',num2str(B),' ',... num2str(a),'A',num2str(b),'B']); %显示步骤及结果 end % --- Executes on button press in pushbutton_reset. function pushbutton_reset_Callback(hObject, eventdata, handles) % hObject handle to pushbutton_reset (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) handles.source = rand4; %重新生成一个随机4位 guidata(hObject, handles); % --- Executes on button press in pushbutton_ans. function pushbutton_ans_Callback(hObject, eventdata, handles) % hObject handle to pushbutton_ans (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) set(handles.text_rez, 'string',['正确答案: ',num2str(handles.source)]); %显示正确答案 %定义生成随机4位的函 function Y=rand4() M=randperm(10); M(find(M==10))=0; Y=M(1:4);
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值