C++如何跳出多层循环
最后更新于:2022-04-01 20:19:40
问题主题:抽签 |
问题描述: 将写有数字的numOfCard个卡片放入口袋中,从口袋中抽取4次卡片,每次记录卡片的数字后将其放回口袋中。设卡片上写的数字为k1、k2、k3...kn,如果这4个数字的和为sum,则输出”Yes”,否则输出”No” 限制条件: 1<=numOfCard<=50 1<=sum<=108 1<=ki<=108 |
样例1: 输入 numOfCard = 3 Sum = 10 K = {1, 3, 5} 输出 Yes 样例2: 输入 numOfCard = 3 Sum = 9 K = {1, 3, 5} 输出 No |
void drawLots() { //从标准输入读入 int numOfCard, sum; int k[MAX_N]; cout<<"输入numOfCard和sum"<<endl; cin>>numOfCard>>sum; cout<<"请输入这sum张卡片的数字"<<endl; for(int i=0; i<numOfCard; i++) { cin>>k[i]; } bool result = false; int _sum = 0; for(int a = 0; a < numOfCard; a ++) { for(int b = 0; b < numOfCard; b ++) { for(int c = 0; c < numOfCard; c++) { for(int d = 0; d < numOfCard; d ++) { _sum = k[a] + k[b] + k[c] + k[d]; if(_sum == sum) { result = true; break; } } } } } if(result){ cout<<"Yes"<<endl; } else cout<<"No"<<endl; } |
void drawLots() { //从标准输入读入 int numOfCard, sum; int k[MAX_N]; cout<<"输入numOfCard和sum"<<endl; cin>>numOfCard>>sum; cout<<"请输入这sum张卡片的数字"<<endl; for(int i=0; i<numOfCard; i++) { cin>>k[i]; } bool result = false; int _sum = 0; for(int a = 0; a < numOfCard; a ++) { for(int b = 0; b < numOfCard; b ++) { for(int c = 0; c < numOfCard; c++) { for(int d = 0; d < numOfCard; d ++) { _sum = k[a] + k[b] + k[c] + k[d]; if(_sum == sum) { result = true; break; } } } } } cout << "_sum:" << _sum << " " << "sum:" << sum << endl; if(result){ cout<<"Yes"<<endl; } else cout<<"No"<<endl; } |
void drawLots() { //从标准输入读入 int numOfCard, sum; int k[MAX_N]; cout<<"输入numOfCard和sum"<<endl; cin>>numOfCard>>sum; cout<<"请输入这sum张卡片的数字"<<endl; for(int i=0; i<numOfCard; i++) { cin>>k[i]; } bool result = false; int _sum = 0; for(int a = 0; a < numOfCard; a ++) { for(int b = 0; b < numOfCard; b ++) { for(int c = 0; c < numOfCard; c++) { for(int d = 0; d < numOfCard; d ++) { _sum = k[a] + k[b] + k[c] + k[d]; if(_sum == sum) { result = true; goto breakLoop; } } } } } breakLoop: cout << "_sum:" << _sum << " " << "sum:" << sum << endl; if(result){ cout<<"Yes"<<endl; } else cout<<"No"<<endl; } |
void drawLots() { //从标准输入读入 int numOfCard, sum; int k[MAX_N]; cout<<"输入numOfCard和sum"<<endl; cin>>numOfCard>>sum; cout<<"请输入这sum张卡片的数字"<<endl; for(int i=0; i<numOfCard; i++) { cin>>k[i]; } bool result = false; bool isBreakLoop = true; int _sum = 0; for(int a = 0; a < numOfCard && isBreakLoop; a ++) { for(int b = 0; b < numOfCard && isBreakLoop; b ++) { for(int c = 0; c < numOfCard && isBreakLoop; c++) { for(int d = 0; d < numOfCard && isBreakLoop; d ++) { _sum = k[a] + k[b] + k[c] + k[d]; if(_sum == sum) { result = true; isBreakLoop = false; } } } } } cout << "_sum:" << _sum << " " << "sum:" << sum << endl; if(result){ cout<<"Yes"<<endl; } else cout<<"No"<<endl; } |