[英]how to get the middle value in real-time/c++
If I get some values from the keyboard, how can I find the middle value between them in real time? 如果我从键盘上获得了一些值,如何实时找到它们之间的中间值?
this is what I have done but without any result :( 这是我所做的,但没有任何结果:(
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;
to clarify: The middle in terms of order they were given 澄清:中间顺序
If you're trying to find the middle value in a container, it's pretty easy: 如果要尝试在容器中查找中间值,这很简单:
#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;
}
Your code has... a lot of problems with pointers. 您的代码有...指针有很多问题。
@Lightness explained it perfectly. @Lightness完美地说明了这一点。 here's another demo (-1 prints the current middle value, -2 exits)
这是另一个演示(-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.