我的 for 循环之后的代码不起作用,for 循环后的打印语句不会被打印
Code after my for loop won't work, the print statement after the for loop does not get printed
我的代码在for循环后不会继续,光标只是闪烁的。我在多个编译器上尝试了它。
Input:
3 50
60 20
100 50
120 30
当我给出此输入时,它需要3个值,而不是在for循环之后打印语句。它只是暂停。:(
这是for循环(图像)
这是我面临的问题。输入后不工作(图像)
这是我的代码。
#include <iostream>
#include <vector>
#include <algorithm>
using std::vector;
double get_optimal_value (int capacity, vector<int> weights,
vector<int> values, int n){
std::cout<<"we are in the function";
double value = 0.0;
int current_weight = 0;
vector<double> v_by_w(n);
for (int i = 0; i < n; ++i)
v_by_w[i] = values[i] / weights[i];
std::cout<<"printing the v/w elements";
for (int i = 0; i < n; ++i)
std::cout<< v_by_w[i] << " ";
while( current_weight < capacity ) {
int maxi = std::max_element(v_by_w.begin(),v_by_w.end()) -
v_by_w.begin();
if((capacity - current_weight) > weights[maxi]){
current_weight += weights[maxi];
value = values[maxi];
} else
value += v_by_w[maxi]*(capacity - current_weight);
v_by_w[maxi] = -1;
}
return value;
}
int main() {
int n;
int capacity;
char ch;
std::cin >> n >> capacity;
vector<int> values(n);
vector<int> weights(n);
for (int i = 0; i < n; i++) {
std::cout<<"hello "<<i ;
std::cin >> values[i] >> weights[i];
}
std::cout<<"we took the values"; //why won't this print?
double optimal_value = get_optimal_value(capacity, weights, values, n);
std::cout.precision(10);
std::cout << optimal_value << std::endl;
return 0;
}
我的目标是打印我们在获取输入后采取的输入。
请让我知道为什么会发生这种情况。我该怎么做才能防止它。
这确实会对我有帮助:)
我尝试在下面运行您的代码:
int main()
{
int n;
int capacity;
char ch;
std::cin >> n >> capacity;
vector<int> values(n);
vector<int> weights(n);
for (int i = 0; i < n; i++) {
std::cout<<"hello "<<i ;
std::cin >> values[i] >> weights[i];
}
std::cout<<"we took the values"; //this is getting printed after taking 2n input from keyboard
}
以下是您程序样本运行的解释:
运行代码时,我会得到空控制台窗口。在这一点上,下面的行期望从键盘上有两个输入:std :: cin>> n>>容量;因此,我给出以下输入(2个空间3输入)2 3//请注意,此输入2分配给变量n,而3分配给可变容量
现在,程序执行控件进入您的前面并打印下面的行代码:std :: cout&lt;&lt;" hello"&lt;
输出你好0现在输入您的两个输入:输出Hello 011 12(11 Space 12 Enter)//击中Enter 11后,将其分配给值[0],然后将12分配给权重[0]
此触发了循环的下一个迭代,控制台窗口的外观如下所示:
你好011 12你好1现在输入您的两个输入:Hello 113 14(13 Space 14 Enter)//击中Enter 13分配给值[1],然后将14分配给权重[1]
现在终止循环,并且在屏幕上打印循环后您的文本。
捕获这是循环的每次迭代,都需要控制台的两个INT输入(std :: cin>> value [i]>>权重[i];)
相关文章:
- 如何循环打印顶点结构
- 在循环C++中指定字符串之后,不会打印该字符串
- 了解嵌套循环打印星号图案
- 在无向图中打印循环
- C++ 无法在字符数组中使用 for 循环打印字母模式
- C++声明双链表,使用两个 for 循环双向遍历列表并打印
- 为什么我在尝试在单向链表中打印元素时会出现这个永无止境的循环
- 如何在 for 循环中的特定时间内获取要打印的额外值
- 如何在循环中打印两个相邻的行,同时在 c++ 中将它们都保留在一行中
- :CIN 不断打印用户在每次循环后输入的内容
- 打印系列时循环出现问题
- 打印循环链表
- 为什么这个 IF 语句在循环内不打印
- 该程序没有产生输出,而是卡在一个循环中,几秒钟后消失并打印被杀死?
- 如何在循环中使用scanf,将值存储到一个变量中,然后打印出来?
- 我的 if 语句打印在我的 while 循环中的每个 if 语句上,无论它是否为假
- 为什么我在使用 for 循环和 cout 命令时没有打印出矢量
- 如何在c++中仅使用for循环打印此代码的垂直直方图
- 递归回溯打印长度为N的二进制数的所有组合,而不使用循环
- 如何编写一个c++数组打印循环,每次迭代从不同的点开始