繁体   English   中英

我的for循环后的代码无法正常工作,for循环后的print语句无法打印

[英]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 >> capacity; 所以我给出下面的输入(2空格3输入)2 3 //请注意,此输入2分配给变量n,3分配给可变容量

现在,程序执行控件进入您的for循环,并在代码下方显示以下行:std :: cout <<“ hello” <

输出hello 0现在输入你的两个输入:输出hello 011 12(11空格12输入)//点击后输入11分配给值[0]而12分配给权重[0]

这会触发下一次循环迭代,控制台窗口如下图所示:

你好011 12你好1现在输入你的两个输入:你好113 14(13空格14输入)//点击后输入13被分配给值[1]而14被分配给权重[1]

现在,循环终止,屏幕上将显示循环后的文本。

这里捕获的是for循环的每次迭代需要来自控制台的两个int输入(std :: cin >> values [i] >> weights [i];)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM