我的 for 循环之后的代码不起作用,for 循环后的打印语句不会被打印

Code after my for loop won't work, the print statement after the for loop does not get printed

本文关键字:打印 循环 for 语句 不起作用 之后 代码 我的      更新时间:2023-10-16

我的代码在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];)