I created a quick method in my program to compute the distance between two points using the distance formula, here’s the code:
#include <iostream>
#include <cmath>
using namespace std;
int distanceFormula(int x1, int y1, int x2, int y2) {
double d = sqrt((x1-x2)^2(y1-y2)^2);
return d;
}
it gives me a compiler error on the line where I declare the d
variable saying that
error: expression cannot be used as a function
.
What does this mean? And what am I doing wrong?
Gilfoyle
3,2622 gold badges45 silver badges80 bronze badges
asked Feb 7, 2014 at 1:24
0
Be careful, (x1-x2)^2
will not do an exponent of 2 here.
See http://www.cplusplus.com/reference/cmath/pow/.
Second, you probably forgot a +
in your expression:
int distanceFormula(int x1, int y1, int x2, int y2) {
double d = sqrt(pow(x1-x2, 2) + pow(y1-y2, 2));
return d;
}
answered Feb 7, 2014 at 1:27
Mr_PouetMr_Pouet
4,0028 gold badges35 silver badges47 bronze badges
5
The compiler error is because 2(y1-y2)
is invalid syntax.
In this case 2
(or perhaps (x1-x2)^2
) is the «expression» and (y1-y2)
is taken as a function call argument list; this grammar production is simply not allowed.
Compare the following form where a binary operator (*
) is introduced, which in turn makes the parser treat the subsequent (y1-y2)
as an expression (bounded by grouping parenthesis) and not a function call. While it won’t do what is desired, as ^
is not exponentiation and the resulting equation is nonsense, it should parse and compile.
sqrt((x1-x2)^2*(y1-y2)^2)
answered Feb 7, 2014 at 1:33
user2864740user2864740
59.6k15 gold badges142 silver badges215 bronze badges
- Forum
- Beginners
- expression cannot be used as a function
expression cannot be used as a function
Hello,
I am exploring Mersenne Twister implementation to use it as a wrapped class that can be reused as a dll for other implementations like C#. I was trying this class and cannot figure out what is wrong. The code listed below and also available @ cpp.sh/4hte. I will appreciate any guidance help with fixing this class.
It gives me error
In member function ‘double Random::GenerateNext()’: 19:19: error: expression cannot be used as a function 20:2: warning: control reaches end of non-void function [-Wreturn-type]
|
|
Well, you have ponters, not objects, remember. You need to dereference pointers first.
Why do you use pointer semantic at all?
|
|
Last edited on
Topic archived. No new replies allowed.
#include <iarduino_Pressure_BMP.h> // Подключаем библиотеку для работы с датчиками BMP180 или BMP280
iarduino_Pressure_BMP sensor(0x76); // Создаём объект sensor для работы с датчиком адрес которого на шине I2C установлен по умолчанию.
#include "FastLED.h"
#define NUM_LEDS 114 // 4*7*4 +2 Количество светодиодов
#define COLOR_ORDER BRG // Порядок цвета для ленты
#define DATA_PIN 6 // Вывод для данных
#define BRI_PIN 3 // Вывод сенсора
CRGB leds[NUM_LEDS]; // Определение СД ленты
// 0,0,0,0
// 1,1,1,1
// 1 2 3 4 5 6 7 8 9 10111213141516171819202122232425262728
byte digits[12][28] = {{0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, // Digit 0
{0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1}, // Digit 1
{1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0}, // Digit 2
{1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1}, // Digit 3
{1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1}, // Digit 4
{1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1}, // Digit 5
{1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, // Digit 6
{0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1}, // Digit 7
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, // Digit 8
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1}, // Digit 9 | Массив числе на 7 сегментах
{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0}, // Digit *0
{0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0}}; // Digit C
// сигнальный провод подключен к 2 пину на Arduino
bool Dot = false; //состояние точек
int last_digit = 0;
// int ledColor = 0x0000FF; // Используемый цвет (in hex)
long ledColor = CRGB::DarkOrchid; // Используемый цвет (in hex)
//long ledColor = CRGB::MediumVioletRed;
//Случайные цвета
long ColorTable[16] = {
CRGB::Amethyst,
CRGB::Aqua,
CRGB::Blue,
CRGB::Chartreuse,
CRGB::DarkGreen,
CRGB::DarkMagenta,
CRGB::DarkOrange,
CRGB::DeepPink,
CRGB::Fuchsia,
CRGB::Gold,
CRGB::GreenYellow,
CRGB::LightCoral,
CRGB::Tomato,
CRGB::Salmon,
CRGB::Red,
CRGB::Orchid
};
void setup(){
Serial.begin(9600);
delay(1000);
sensor.begin(); // Инициируем работу с датчиком (начальная высота по умолчанию = 0 метров)
LEDS.addLeds<WS2812B, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS); // Выбор типа ленты
LEDS.setBrightness(55); // Установка яркости
}
// Convert temp to array needet for display
void TempToArray(){
// tmElements_t tm;
// RTC.read(tm);
// if (tm.Second != 27) {
// TempShow = false;
// return;
// }
/*
if (time.seconds !=20||time.seconds !=50){
TempShow = false;
return;
}
*/
/*
// TempShow = true;
// int t = RTC.temperature();
int t = sensor.temperature;
// int celsius = (t / 4.0) * 100;
int celsius = t;
*/
int celsius = sensor.temperature;
// Serial.print("Temp is: ");Serial.println(celsius);
// Serial.println(sensor.temperature);
Serial.println(celsius);
int cursor = 114; // last led number
leds[57]=0x000000;
leds[56]=0x000000;
for(int i=1;i<=4;i++){
int digit = celsius % 10; // get last digit in time
if (i==1){
Serial.print("Digit 4 is : ");Serial.print(digit);Serial.print(" ");
cursor = 86;
for(int k=0; k<=27;k++){
Serial.print(digits[11][k]);
if (digits[11][k]== 1){leds[cursor]=ledColor;}
else if (digits[11][k]==0){leds[cursor]=0x000000;};
cursor ++;
};
Serial.println();
}
else if (i==2){
Serial.print("Digit 3 is : ");Serial.print(digit);Serial.print(" ");
cursor =58;
for(int k=0; k<=27;k++){
Serial.print(digits[10][k]);
if (digits[10][k]== 1){leds[cursor]=ledColor;}
else if (digits[10][k]==0){leds[cursor]=0x000000;};
cursor ++;
};
Serial.println();
}
else if (i==3){
Serial.print("Digit 2 is : ");Serial.print(digit);Serial.print(" ");
cursor =28;
for(int k=0; k<=27;k++){
Serial.print(digits[digit][k]);
if (digits[digit][k]== 1){leds[cursor]=ledColor;}
else if (digits[digit][k]==0){leds[cursor]=0x000000;};
cursor ++;
};
Serial.println();
}
else if (i==4){
Serial.print("Digit 1 is : ");Serial.print(digit);Serial.print(" ");
cursor =0;
for(int k=0; k<=27;k++){
Serial.print(digits[digit][k]);
if (digits[digit][k]== 1){leds[cursor]=ledColor;}
else if (digits[digit][k]==0){leds[cursor]=0x000000;};
cursor ++;
};
Serial.println();
}
celsius /= 10;
};
};
void loop (){
TempToArray();
FastLED.show();
}
The essence of the program: get a map, where the values are char from the passed string, and the key is the number of these values in the string
using namespace std;
map<char, int> is_merge(const string& s) {
map<char, int> sCount {};
for (auto lp : s) {
if (find_if(sCount.begin(), sCount.end(), lp) != sCount.end()) {
sCount[lp] += 1;
} else {
sCount.insert(make_pair(lp, 0));
}
}
return sCount;
}
int main()
{
string test = "aba";
map <char, int> res = is_merge(test);
for (auto lp : res) {
cout << lp.first << ":" << lp.second << endl;
}
return 0;
}
But an error occurs in the console: /usr/include/c++/12/bits/predefined_ops.h:318:30: error: expression cannot be used as a function 318 | { return bool(_M_pred(*__it)); } | ~~~~~~~^~~~~~~
>Solution :
std::find_if
takes a predicate not a value. Hence the error that lp
is not a callable. To find a key in a map you should use std::map::find
because it is O(logn)
compared to O(n)
for std::find
/std::find_if
(as a rule of thumb you can remember: If a container has a member function that does the same as a generic algorithm the member function is at least as effcient, often better).
However, there is not need to check if the key is present via find
. The function can be this:
map<char, int> is_merge(const string& s) {
map<char, int> sCount {};
for (auto lp : s) {
++sCount[lp];
}
return sCount;
}
std::map::operator[]
already does insert an element when none is found for the given key. You don’t need to do that yourself.
PS: And if you do call insert
then there is no need for std::make_pair
: sCount.insert({lp, 0});
. std::make_pair
is for when you need to deduce the type of the pair from arguments to std::make_pair
, but you don’t need that here.
PPS: And if you do use std::find
you need to consider that the element type of your map is std::pair<const char, int>
, not char
.
Loading