第五篇——C++實現四則運算


寫一個能自動生成小學四則運算題目的命令行 “軟件”, 分別滿足下面的各種需求。下面這些需求都可以用命令行參數的形式來指定: a) 除了整數以外,還要支持真分數的四則運算。 (例如: 1/6 + 1/8 = 7/24) b) 讓程序能接受用戶輸入答案,並判定對錯。 最后給出總共 對/錯 的數量。 c) 逐步擴展功能和可以支持的表達式類型,最后希望能支持下面類型的題目 (最多 10 個運算符,括號的數量不限制): 25 - 3 * 4 - 2 / 2 + 89 = ? 1/2 + 1/3 - 1/4 = ? (5 - 4 ) * (3 +28) =?d) 一次可以批量出 100 道以上的題目,保存在文本文件中, 並且保證題目不能重復,(1+2) 和 (2+1) 是重復的題目。 怎么保證題目不重復呢,請看詳細題目要求。

#include<iostream.h>
#include<stdlib.h>
#include<conio.h>

void DealFenshu(int m, int a[][2])
{
for(int p=0;p<m;p++)
{
int i=(int)rand()%10;
int j=(int)rand()%10;
while(j==0||i>=j)
{
i=(int)rand()%10;
j=(int)rand()%10;
}
int x=(int)rand()%10;
int y=(int)rand()%10;
while(y==0||x>=y)
{
x=(int)rand()%10;
y=(int)rand()%10;
}
int k=(int)rand()%100/25;
switch(k)
{
case 0:
cout<<"("<<i<<"/"<<j<<")"<<"+"<<"("<<x<<"/"<<y<<")"<<"=";
a[p][0]=i*y+x*j;
a[p][1]=j*y;
break;
case 1:
cout<<"("<<i<<"/"<<j<<")"<<"-"<<"("<<x<<"/"<<y<<")"<<"=";
a[p][0]=i*y-x*j;
a[p][1]=j*y;
break;
case 2:
cout<<"("<<i<<"/"<<j<<")"<<"*"<<"("<<x<<"/"<<y<<")"<<"=";
a[p][0]=i*x;
a[p][1]=j*y;
break;
case 3:
a[p][0]=i*y;
a[p][1]=j*x;
cout<<"("<<i<<"/"<<j<<")"<<"/"<<"("<<x<<"/"<<y<<")"<<"=";
}

if(p%5==4)
{
cout<<endl;
}
else
{
cout<<‘\t‘;
}
}

}
void DisplayFenshu(int a[][2],int w,int m)
{
if(w==1)
{
for(int q=0;q<m;q++)
{
if(a[q][0]==0)
cout<<"0"<<‘\t‘;
else
cout<<a[q][0]<<"/"<<a[q][1]<<‘\t‘;
if(q%5==4)
{
cout<<endl;
}
}
}
else
{};
}
void DealInt(int m,int a[])
{

for(int p=0;p<m;p++)
{
int i=(int)rand()%10;
int j=(int)rand()%10;
int k=(int)rand()%100/25;
switch(k)
{
case 0:
cout<<i<<"+"<<j<<"=";
a[p]=i+j;
break;
case 1:
cout<<i<<"-"<<j<<"=";
a[p]=i-j;
break;
case 2:
cout<<i<<"*"<<j<<"=";
a[p]=i*j;
break;
case 3:
try
{
a[p]=i/j;
cout<<i<<"/"<<j<<"=";
}
catch(...)
{
p--;
}

}

if(p%5==4)
{
cout<<endl;
}
else
{
cout<<‘\t‘;
}
}
}
void DisplayInt(int a[],int w,int m)
{
if(w==1)
{
for(int q=0;q<m;q++)
{
cout<<a[q]<<‘\t‘;
if(q%5==4)
{
cout<<endl;
}
}
}
else
{};
}
void main()
{
int p;
do
{
system("cls");
int a[1000],b[1000][2];
int m,n,w;
cout<<"請輸入生成的四則運算題個數:";
cin>>m;
cout<<endl;
cout<<"請輸入要生成的四則運算種類(輸入1為整數,否則為真分數):";
cin>>n;
cout<<endl;
if(n==1)
{
DealInt(m,a);
cout<<endl;
}
else
{
DealFenshu(m,b);
cout<<endl;
}
cout<<"是否輸出答案(輸入1則輸出答案否則不輸出答案)"<<endl;
cin>>w;
if(n==1)
{
DisplayInt(a,w,m);
}
else
{
DisplayFenshu(b,w,m);
}
cout<<endl;
cout<<"是否繼續生成運算題(輸入1則生成否則不生成)"<<endl;
cin>>p;
cout<<endl;
}while(1==p);

}

若題目要求100道自動生成,即可輸入100.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM