簡體   English   中英

如何實時獲取中間值/ C ++

[英]how to get the middle value in real-time/c++

如果我從鍵盤上獲得了一些值,如何實時找到它們之間的中間值?

這是我所做的,但沒有任何結果:(

float *p=new float;  //p points to the first element
float *my;
std::cin >> my;
vector<float*>V;
V.push_back(my);
std::vector<float*>::iterator it;
p=my;

 while(my){
   it=V.begin()+1;
 }

int M =(*it-p)/2;

delete[] p;

澄清:中間順序

如果要嘗試在容器中查找中間值,這很簡單:

#include <iostream>
#include <vector>

int main() {
    std::vector<float> v{1,2,3,4,5};

    // Output:     (1,2,3,4,5)
    //          3       ^ 
    std::cout << v.at(v.size()/2) << std::endl;

    // Now a user provides another value, maybe
    v.push_back(6);

    // Output:     (1,2,3,4,5,6)
    //          4         ^
    std::cout << v.at(v.size()/2) << std::endl;
}

演示版

您的代碼有...指針有很多問題。

@Lightness完美地說明了這一點。 這是另一個演示(-1顯示當前中間值,-2退出)

#include <iostream>
#include <vector>

int main() {
    std::vector<float> values;
    float value;

    while(std::cin >> value) {
        if(value == -1 && values.size() > 0)
            std::cout << "mid = " << values.at(values.size() / 2) << std::endl;
        else if (value == -2)
            break;
        else
            values.push_back(value);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM