簡體   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