问题: 你的程序是使用蛮力方法来找到生命,宇宙和一切的答案。更确切地说......从输入到输出重写小数字。读取数字42后停止处理输入。输入的所有数字都是一位或两位数的整数。
实施例 输入: 1 2 88 42 99
输出: 1 2 88
所以这就是问题,但我仍然是初学者,无法拥有这样的输入标签。在我的程序中,我应该如何修改它,使它在42之后仍然接受数字,但是,它不打印它们?目前我只能在42处终止输入。
#include <iostream>
using namespace std;
int main()
{
int A[100], num, i=0,k,count;
for(count = 0; count != 1;){
cin >> k;
if (k!=42){
A[i] = k;
i++;
}
else
count =1;
}
cout << endl;
for (count = 0; count <i; count ++){
cout << A[count] << endl;
}
}
答案 0 :(得分:1)
你根本不必使用数组。您可以在阅读后立即打印该值。 当您阅读42 时退出。这可能会对你有帮助。
#include <iostream>
using namespace std;
int main() {
// your code goes here
int n ;
for(; ;) {
cin >> n ;
if(n == 42) {
return 0 ;
}
cout << n << endl ;
}
return 0;
}
答案 1 :(得分:0)
非常确定最简单的方法是简单地询问用户需要输入多少个号码。
#include <iostream>
using namespace std;
int main()
{
int A[100], k, count;
cout << "How many numbers do you want to enter ? ";
cin >> count; //this is to count how many numbers the user wants to enter
for(int i(0); i < count; ++i) //put all the numbers user enters in your array
{
cin >> k;
A[i] = k;
}
cout << endl;
for (int i(0); i < count; ++i)
{
if (A[i] == 42) //if the element at index i is == 42 then stop displaying the elements
break;
else
cout << A[i] << " "; //else display the element
}
cout << endl;
return 0;
}
否则你需要把所有东西放在一个字符串中并解析它,我不太确定这是怎么回事,因为我也是初学者。
编辑: 实际上你走了,我认为这是正确的,并且完全符合你的要求。 请记住,如果用户输入p.e&#34; 1 88 442&#34;它将输出&#34; 1 88 4&#34;因为它找到了&#34; 42&#34; in&#34; 442&#34;。但它应该没问题,因为你精确的输入数字应该只有两位数。
#include <iostream>
using namespace std;
int main()
{
string k;
getline(cin, k);
cout << endl;
for (unsigned int i(0); i < k.length(); ++i)
{
if (!((k[i] == '4') && (k[i+1] == '2'))) //if NOT 4 followed by 2 then display
cout << k[i];
else
break; //else gtfo
}
cout << endl;
return 0;
}
答案 2 :(得分:0)
使用glp_iocp iocpParm = new glp_iocp();
iocpParm.setPresolve(GLPK.GLP_ON);
GLPK.glp_init_iocp(iocpParm);
ret = GLPK.glp_intopt(lp, iocpParm);
值来控制代码的执行。
glp_intopt: optimal basis to initial LP relaxation not provided
The problem could not be solved
(我的代码未经过测试)
答案 3 :(得分:0)
你必须要有一些状态,看看你是否已经看过42
,只有在你没有
#include <iostream>
int main()
{
bool output = true;
for (int n; std::cin >> n;)
{
output &= (n != 42);
if (output)
{
std::cout << n << std::endl;
}
}
return 0;
}