c++指针、文件读写小程序

最近用c++写了一个小程序,程序主要目的是显示数列中的两个数字,然后让用户猜第三个数字是什么?

要求:

1)要求有6个数列,每个数列存在数组或者向量中。

2)每次显示的数列是系统随机抽选的数列并且每次抽选的数列中的数字也是随机的。

3)当用户回答正确或者错误之后询问用户是否继续,当用户输入Y/y是表示用户希望继续,当用户输入其他程序退出。

4)程序最后要返回用户的得分,为用户回答对的次数与用户回答的次数的比值。

5)程序开始要求用户输入用户名,程序的最后将用户名,用户答对的次数以及用户回答的总次数存入名字为seq_data.txt的文件中。

6)忘了一点,要求有一个指针类型的数组存放每个数列的首地址,在调用数列的时候用这个指针数组调用。


下面是整个程序,先说明,本程序是在vs2012环境中运行,建立c++工程,并在头文件stdafx.h中加入以下头文件:

#pragma once

#include "targetver.h"
#include "vector"

#include <string>
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include<fstream>
using namespace std;
程序主体:

// test.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"


int _tmain(int argc, _TCHAR* argv[])
{
	const int seq_cnt=6;
	const int seq_size=8;
	int fibonacci[seq_size]={1,1,2,3,5,8,13,21};
	int lucas[seq_size]={1,3,4,7,11,18,29,47};
	int pell[seq_size]={1,2,5,12,29,70,169,408};
	int triangular[seq_size]={1,2,6,10,15,21,28,36};
	int square[seq_size]={1,4,9,16,25,36,49,64};
	int pentagonal[seq_size]={1,5,12,22,35,51,70,92};
	int *seq_addrs[seq_cnt]={fibonacci,lucas,pell,triangular,square,pentagonal};

 	int i=0;
	string user_name;

	bool tr=true;
	char t;
	int user_value,user_tries=0,user_right=0;
	float user_score;
	cout<<"你的名字是:";
	cin>>user_name;
	
	while(i<seq_cnt&&(tr==true))
	{
		vector<int> *pv=0;
		
		int q=rand()%6;
		int *p=seq_addrs[q];
		int k=rand()%6;
		user_tries++;
		cout<<"数列的前两个数为"<<*(p+k)<<","<<*(p+k+1)<<",下一个数为:";
	cin>>user_value;
	cout<<'\n';
	if(user_value==(*(p+k+2)))
		{
			cout<<"答对了,是否继续!Y/N"<<"\t";
			user_right++;
			cin>>t;
			if(t=='Y'||t=='y')
				tr=true;
			else	
				tr=false;	
	}
	else
	{
		cout<<"答错了,是否继续!Y/N"<<"\t";
		cin>>t;
			if(t=='Y'||t=='y')
				tr=true;
			else
				tr=false;
		
	}
		
		
	}
	if(user_tries==seq_cnt)
		cout<<"次数已达到上限!!!"<<"\n";
	user_score=(float)user_right/user_tries*100;
	cout<<"\n"<<"\n";
	cout<<"您最后得分是:"<<user_score<<"\n";
	ofstream outfile("seq_data.txt",ios_base::app);
	if(!outfile)
		cout<<"文件打开失败!!!";
	else
	{
		outfile<<"用户名:"<<user_name<<"\t"<<"回答次数:"
			<<user_tries<<"\t答对的次数:"<<user_right<<"\n"<<endl;
	}
	return 0;
}



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值