Error expected primary expression before float

I cannot seem to find why I am getting the build error expected primary-expression before "float" In this implementation... using namespace std; class Point{ public: Point(float X = 0.0, flo...

I cannot seem to find why I am getting the build error

expected primary-expression before «float»

In this implementation…

using namespace std;

class Point{
public:

Point(float X = 0.0, float Y = 0.0);

void set(float X, float Y);
void setX(float X);
void setY(float Y);

void get(float * P_x, float * P_y);
float getX();
float getY();

float * pX();
float * pY();

SDL_Point returnSDL();

private:
float x;
float y;
};


class Vector : public Point{
public:
    Vector(float X = 0.0, float Y = 0.0);
};

 ///The errors occur in this constructor...
Vector::Vector(float X, float Y) : Point(float X, float Y){

}

Im still learning about the finer points of classes and would appreciate any help. I know it has something to do with the inheritance because when Vector doesn’t inherit Point the program builds normally. As far as i can tell this is the correct syntax and implementation of inheritance. Web help i have found cannot answer so far.

asked Apr 23, 2015 at 11:42

Svihuroid's user avatar

1

///The errors occur in this constructor...
Vector::Vector(float X, float Y) : Point(float X, float Y){

}

There are two similar constructions in this fragment of code:
Vector::Vector(float X, float Y) and : Point(float X, float Y):

  • the first one (Vector::Vector(float X, float Y)) is the declaration of the constructor of class Vector;
  • the other one (: Point(float X, float Y)) is a function call; a call of the constructor of class Point; notice the colon (:) that introduce the list of member initializers.

Now, if you see the difference between the two (function/method declaration or definition vs. function/method call) you can find the error yourself: the compiler expects expressions and not types in the arguments list of the call to the Point::Point() constructor.

// Look, ma! No errors!
Vector::Vector(float X, float Y) : Point(X, Y) {

}

For more information take a look at the documentation page about constructors and member initializer lists.

answered Apr 23, 2015 at 12:05

axiac's user avatar

axiacaxiac

65.7k9 gold badges98 silver badges126 bronze badges

You are confusing declaring a function and using a function. When you declare a function you need to tell the compiler what the types of the parameters are.

Vector::Vector(float X, float Y)

Now in the member initialization part you have

: Point(float X, float Y)

Here you are adding types to the function call which is not what you want to do. When you call a function you just pass the values/variables to it.

: Point( X, Y)
        ^  ^ no type here as we just pass X and Y to the Point constructor.

answered Apr 23, 2015 at 12:03

NathanOliver's user avatar

NathanOliverNathanOliver

168k28 gold badges280 silver badges387 bronze badges

Содержание

  1. Error expected primary expression before float
  2. Error expected primary expression before float
  3. Я не понимаю ошибки компилятора
  4. Решение
  5. Другие решения
  6. Fix “Expected Primary-Expression Before” in C++ or Arduino
  7. How to fix “Expected Primary-Expression Before” error?
  8. Type 1: Expected primary-expression before ‘>’ token
  9. Type 2: Expected primary expression before ‘)’ token
  10. Type 3: Expected primary-expression before ‘enum’
  11. Type 4: Expected primary expression before ‘.’
  12. Type 5: Expected primary-expression before ‘word’
  13. Type 6: Expected primary-expression before ‘else’
  14. Conclusion
  15. Arduino.ru
  16. Регистрация новых пользователей и создание новых тем теперь только на новом форуме https://forum.arduino.ru
  17. forum.arduino.ru
  18. не могу найти ошибку в синтаксисе

Error expected primary expression before float

I am running into errors when I am compiling code in CodeBlocks, and I am not sure what I am doing wrong. I am creating this simple program for a class, but it is pulling up an error saying on line 27 (I have bolded it in the code): «error: expected primary-expression before ‘float’ for all 3 variables. Someone help me with this? I’m completely lost.

I suspect what you actually saw was a function declaration. That’s not a call.

But yes, I’d strongly advise going back to your textbook to be absolutely clear in your mind what the difference between the two things is.

I just adjusted the code to how I am used to programming. Is this still sufficient? It runs and outputs the desired results.

I just didn’t understand what he was doing by declaring a variable like that up above main. I couldn’t see what he wanted to do with it, so I just removed the mileage variable and set the mpg to what mileage would have been.

Well, it looks like it’ll work fine, although it no longer calls a function to do the calculation. If the purpose of the exercise was to learn about functions, then it’s probably not much use now 😉

I just didn’t understand what he was doing by declaring a variable like that up above main. I couldn’t see what he wanted to do with it, so I just removed the mileage variable and set the mpg to what mileage would have been.

mileage isn’t a variable — it’s a function. That bit above main is declaring a function called mileage, and declaring which arguments it takes and what it returns.

Источник

Error expected primary expression before float

Hey,
I found this site because I wanted to start C++. I read half the tutorials and made a program with the info that I have. The part i screwed up on are the functions. I wrote them in but when they didn’t work I decided to not use them, but they still exist. I used one near the bottom of my code. I keeping getting the error: expected primary-expression before ‘float’ and im not sure what I am doing wrong. I probably didn’t code this in the best manner but oh well. what can I say im a noob.:) help would be greatly appreciated, and any other suggestions!
Thanks

using namespace std;

long operation;
float a;
float b;
float y;
float x;
float s;
float inter; // intercept
int c; // if == 1 goto
int k;
float Ia; //numerator
float Ib; //denominator
float r; //result after the ia/ib
int t; //if == 1 move on
float l;
float m;

int add (int Aa, int Ba)
<
Aa = a;
Ba = b;
int adda;
adda=Aa+Ba;
return (adda);
>
int dived (int Da, int Db)
<
Da = a;
Db = b;
int d;
d=Da/Db;
return (d);
>
int multiply (int Ma, int Mb)
<
Ma = a;
Mb = b;
int r;
r=Ma*Mb;
return (r);
>
int subtraction (float Sa, float Sb)
<
Sa = l;
Sb = m;
int s;
s=Sa-Sb;
return (s);
>
//int figure (int Ic, int Id)
// <
//cout > Ic;
//cout > Id;
//s = Ic/Id;
//return(s);
//>
int main ()
<
start:
cout > operation;
if (operation==1)
<
cout > a;
cout > b;
cout > a;
cout > b;
cout > a;
cout > b;
cout > a;
cout > b;
cout > x;
cout > k;
if (k!=1) <
goto intercept;
>
if (k==1) <
cout > Ia;
cout > Ib;
r = Ia/Ib;
cout > s;
cout > inter;
y = s*x+inter;
cout > t;
if (t==1) <
c=1;
>
if (c==1) <
goto start;
>

>
if (operation==6) <
return 0;
>
if (operation==7) <
cout > l;
cout > m;
cout

Other things I noticed:
— Your variable names are not very descriptive
— You use the goto keyword in cases where it is not necessary (generally use a loop instead)
— You use several magic numbers
— Your functions create many temporary variables for no reason

Источник

Я не понимаю ошибки компилятора

Это домашнее задание, поэтому я не хочу, чтобы вы полностью написали недостающий код. Но мне нужен довольно сильный толчок, потому что я новичок и мне нужно ознакомиться с тем, что я делаю.

Этот формат используется в AddDetailsblablablafunction ()

Линия 51 является прототипом функции

Строка 85 находится в главном модуле и вызывает функцию AddDetailToAccumulators ()

Ошибки компилятора перечислены следующим образом:

Я надеюсь, что мое форматирование хорошо. 🙂

РЕДАКТИРОВАТЬ: BurningLights, я люблю тебя!

Решение

Итак, вот почему вы получаете свои ошибки.

Для первой и второй ошибки ваш *float должно быть float * , дела *float ничего не значит для компилятора и поэтому выдает ошибку. дела float * с другой стороны, сообщает компилятору, что вы хотите указатель на число с плавающей точкой, и это совершенно правильно.

Что касается третьей и четвертой ошибок, вы допустили ошибку при включении типов в вызов функции. Не делай этого! Это генерирует ошибку. Просто удалите типы так, чтобы это выглядело как AddDetailToAccumulators(totpayrate, p); и это исправит ваши ошибки, если допустить, что totpayrate и p являются указателями на числа с плавающей точкой, определенные в вашей основной функции.

Для пятой ошибки вы пытаетесь добавить два указателя вместе. Это не работает! Я предполагаю, что вы пытаетесь использовать указанные значения, поэтому вам нужно добавить оператор разыменования (*), чтобы он выглядел следующим образом: *totpayrate = *p + *totpayrate; ,

Для шестой ошибки и предупреждений, ваша строка формата » %-7s%7f%4fn» говорит fprintf() что он должен ожидать строковый аргумент, а затем два аргумента float / double, чтобы иметь возможность выписать в выходной поток в указанном формате. Однако вы продолжаете указывать только один аргумент с плавающей точкой. Я не могу точно сказать вам, как это исправить, так как я не знаю намерения строки формата или то, что вы должны печатать. Я могу вам сказать, что вам нужно либо изменить строку формата, чтобы ей требовалось только одно значение с плавающей точкой, но не строку, или добавить дополнительные параметры в ваш файл. PrintSummaryReport() функция, чтобы вы могли дать fprintf() что ваша строка формата говорит о том, что она должна ожидать.

Другие решения

В строке 51 компилятор сообщает вам, что используется оператор косвенного обращения (*), но у вас нет объявления типа перед ним, поэтому перейдите на float * p.

В строке 173 сообщается, что вы не указали достаточно аргументов формата для строки REPLNEFORMT3, она ожидает 3, но вы дали только один.

Источник

Fix “Expected Primary-Expression Before” in C++ or Arduino

“Expected primary-expression before ‘some‘ token” is one of the most common errors that you can experience in Arduino code. Arduino code is written in C++ with few additions here and there, so it is a C++ syntax error. There are multiple versions of this error, depends on what is it that you messed up. Some are easy to fix, some not so much.

Most of the times (but not always), the error occurs because you have missed something or put it at the wrong place. Be it a semicolon, a bracket or something else. It can be fixed by figuring out what is that you missed/misplaced and placing it at the right position. Let us walk through multiple versions of the error and how to fix them one by one.

We all like building things, don’t we? Arduino gives us the opportunity to do amazing things with electronics with simply a little bit of code. It is an open-source electronics platform. It is based on hardware and software which are easy to learn and use. If I were to explain in simple language what Arduino does – it takes an input from the user in different forms such as touch or light and turns it into an output such as running a motor. Actually, you can even post tweets on Twitter with Arduino.

Table of Contents

How to fix “Expected Primary-Expression Before” error?

I’ll walk you through multiple examples of where the error can occur and how to possibly fix it. The codes that I use as examples in this article are codes that people posted on forums asking for a solution, so all credits of the code go to them. Let’s begin.

Type 1: Expected primary-expression before ‘>’ token

This error occurs when when the opening curly brackets ‘<‘ are not properly followed by the closing curly bracket ‘>’. To fix this, what you have to do is: check if all of your opening and closing curly brackets match properly. Also, check if you are missing any curly brackets. There isn’t much to this, so I’ll move on to the other types.

Type 2: Expected primary expression before ‘)’ token

Example 1: All credits to this thread. Throughout all of my examples, I will highlight the line which is causing the issue with red.

Solution 1:

The error occurs in this code because the rainbow function is supposed to have a variable as its argument, however the argument given here is ‘uint8_t’ which is not a variable.

Here all you have to do is define uint8_t as a variable first and assign it a value. The code will work after that.

Type 3: Expected primary-expression before ‘enum’

Example 1: All credits to this thread.

Solution 1:

The “expected primary-expression before ‘enum’ ” error occurs here because the enum here has been defined inside a method, which is incorrect. The corrected code is:

Note: Another mistake has been fixed in this code i.e. the space in “Range Rover” variable. Variable names cannot contain spaces.

Type 4: Expected primary expression before ‘.’

Example 1: All credits go to this thread.

Solution 1: Here the error occurs because “square” is being used as an object, which it is not. Square is a type, and the corrected code is given below.

Type 5: Expected primary-expression before ‘word’

Example 1: All credits go to this thread.

Solution 1:

Here, they are incorrectly using string inside wordLengthFunction().

Fixing it is simple, simply replace

Type 6: Expected primary-expression before ‘else’

Example 1: All credit goes to this thread.

Solution 1:

This code is not correct because after the if statement is closed with ‘>’ in this code, there are two statements before the else statement starts. There must not be any statements between the closing curly bracket ‘>’ of if statement and the else statement. It can be fixed by simply removing the part that I have marked in red.

Conclusion

And that’s it, I hope you were able to fix the expected primary-expression before error. This article wasn’t easy to write – I’m in no way an expert in C++, but I do know it to a decent level. I couldn’t find any articles related to fixing this error on the internet so I thought I’d write one myself. Answers that I read in forums helped me immensely while researching for this article and I’m thankful to the amazing community of programmers that we have built! If you would like to ask me anything, suggest any changes to this article or simply would like to write for us/collaborate with us, visit our Contact page. Thank you for reading, I hope you have an amazing day.

Also, tell me which one of the 6 types were you experiencing in the comments below.

Источник

Arduino.ru

Регистрация новых пользователей и создание новых тем теперь только на новом форуме https://forum.arduino.ru

forum.arduino.ru

не могу найти ошибку в синтаксисе

Доброго времени суток всем

Пробую подключить датчик температуры DS18B20 к ардуине меге

определить датчик по первому куску кода смог, только кавычки в коде все ухеали (там, в примере) и пробел лишний был. Ну да бог с ним, разобрался.

А вот получить данные от датчика никак не могу, ошибка на ошибке.

Вот код, который пытаюсь скомпилировать:

а вот ошибки, которые выдает Arduino IDE:

никак не пойму, где он находит эту ‘’ и откуда вылезли ‘u2014’

на СИ раньше не программировал, это первый опыт подобного рода, так что я весь потерялся

направьте на путь истинный, где копать? 🙂

В каталоге, в котором установлена ваша Arduino IDE, найдите подкатклог libraries, а в нем — OneWire. Там, по идее, должен быть файл in_Dallas.cpp (какая-то хрень для поддержки микросхем от Dallas Semiconductor??), в котором компиллятор находит ошибки.

Кстати, может быть, у вас библиотека OneWire какая-то левая? Откуда брали?

ЗЫ: OneWire.zip по вышеприведенной ссылке? 2008 года выпечки? Возьмите что-нибудь посвежее. Отсюда, например (ссылка для скачки на словах «The latest version of the library is «)

неа, in_Dallas — это имя скетча, другого с этим именем ничего нет, но и в папке со скетчем собсно файл in_Dallas.ino

а вот in_Dallas.cpp нигде не вижу, может этот файл при компиляции где-то создается?

Arduino IDE вроде использует компилятор от СИ (могу и ошибаться)

понять бы на что конкретно ругается

первая ошибка возникает на 62 строке, а там комментарий, ни хрена не понимаю

ежели закомментировать строку после комментария (return tr—(float)0.25+(cpc — cr)/(float)cpc;), то первая ошибка уходит, такое ощущение, что ругается именно на это сложное выражение.

А библиотеку OneWire я брал с разных мест, в частности с той страницы, откуда пример взят, в поведении скетча при этом ничего не менялось.

По Вашей ссылке версию тоже забирал, она щас и стоит. Версия Arduino IDE кстати, стоит 1.000

На более ранних версиях IDE (0022, 0023) не пробовали?

ЗЫ: загрузил-таки этот скетч к себе. Получил ту же хрень. Пришлось присмотреться поближе. Выяснилось — у вас в некоторых местах дефисы вместо минусов стоят (в редакторе IDE они сужественно — арза в полтора — длиннее минусов).

Перепишите «гнилые» символы

твою ж налево, вот никак не мог подумать на такую разницу, все-таки гнилой пример, ох гнилой

спасибо, пойду переправлять

а из ранних пробовал 0017, то же самое

такс, получилось, теперь надо разобраться в полученных данных, как-то он мне неправильно кажет (40 градусов, а если взяться за датчик пальцами, то все 90)

може конечно с подключением датчика чой-то не то, надо поглядеть

за подсказку спасибо, эту гниль я не разглядел

мне вот непонятно что это за арифметические действия такие :

в описании языка не нашел, что это

мне вот интересно, а расчет температуры хоть верный?

//calculate the temperature based on this formula:
//TEMPERATURE = TEMP READ — 0.25 + (COUNT PER Celsius Degree — COUNT REMAIN)/ (COUNT PER Celsius Degree)
return tr-(float)0.25+(cpc — cr)/(float)cpc;

не блин, я шизею

при комнатной температуре данные выходят:

почти как у автора в статье

пойду искать ошибку в формуле

мне вот непонятно что это за арифметические действия такие :

Читаем arduino.ru/Reference/Boolean про ! (логическое отрицание)

При этом держим в уме, что в ардуино нет отдельного типа Boolean. Любое числовое значение отличное от нуля будет интерпретироватся как «Истина», а ноль как «Ложь». Точно так же и любой логический оператор можно рассматривать как числовую функцию, которая возвращает либо 0, либо единицу.

Поэтому эту срочку можно интепретировать так: !tr вернет ноль, если tr не равно нулю, и единицу если tr равно нулю. Потом к ней прибавится единица и все это сохранится опять в tr. В итоге в tr будет 1, если изначально было 0, и будет 2 если изначально было не ноль.

А еще лучше, напишите скетчик, который который будет возвращать значения tr, !tr, !tr+1 для разных значений tr, поиграйтесь, поймете.

в описании языка не нашел, что это

Плохо искали. Arudino.ru это не единственное место где описана ардуина. Есть еще первоисточник http://arduino.cc/en/Reference/Bitshift

А еще можно вспомнить, что ардуино это «такой упрощенный C/C++» и почитать его справочники по ним. Погуглите что-то типа «операторы сдвига в C C++». Вот, например www.softsvet.ru/2007/08/07/operatory_sdviga_v_s_i_s.html

Многие «зубодробительные» вещи типа работы с указателями можно подсмотреть «там». Плюс это пригодится если прийдется разбиратся в каких-то примерах/объяснениях которые пишут «настоящие» микроконтрольщики.

мне вот непонятно что это за арифметические действия такие :

в описании языка не нашел, что это

! — инвертирование. Например, tr=85 (0x55, b01010101) !tr=-86 (0xAA, b10101010) — каждый бит текущего значения меняется на противоположный.

>> — смещение значения переменной на n бит вправо. Например, tr=85 (0x55,b01010101) tr>>1=42 (0x2A, b00101010)

пойду искать ошибку в формуле

Я бы вам посоветовал приглядеться к примеру DS18x20_Temperature из библиотеки OneWire. Он точно работоспособный и отталкиваясь от него вполне можно расширить функциональность в нужную сторону.

А на заборах скетчи срисовывать- занятие весьма нерациональное.

не блин, я шизею

Вот главврачиха — женщина —
пусть тихо, но помешана, —
Я говорю: «Сойду с ума!» — она мне: «Подожди!»

А зачем так сложно?

В вся кухня работы с датчиком уже «упрятанна под капот». Сразу умеет возвращать как в цельсиях, так и в фаренгейтах (в примере, как раз, работа с цельсиями).

! — инвертирование. Например, tr=85 (0x55, b01010101) !tr=-86 (0xAA, b10101010)

Может вы и правы (поэтому конечно лучше написать демо-скетч и проверить «как оно взаправду»), но я опирался, в своем ответе на http://arduino.cc/en/Reference/HomePage где ! находится в разделе логических операторов, поэтому логично предположить именно поведения «логического» оператора.

А вот то что вы описали больше похоже на оператор Bitwise NOT (

) operator из раздела «bitwise Operators»

В разделе warning (предупреждение, внимание) упоминается что не стоит путать ! и

. Они хоть и похожи, но. нужно знать какой когда. В переводе, к сожалению, это предупреждение уже отсутсвует. Как и, по большому счету весь раздел «Bitwise Operators»

Честно говоря, шевелился червячок сомнения при написании, но я его героически растоптал. Ибо — лень!

Спасибо за поправку, leshak.

У меня тоже. Поэтому и делал оговорку про «напишите проверочный скетч». Даже сейчас, не смотря на все свои доводы, я не уверен что я прав (нет ардуины под рукой что-бы проверить).

Но, по как минимум в одном случае мы будем правы оба: если «входящий tr будет 0 или 1». Тогда оба «наши» оператора будут работать идентично 😉

спасибо за разбор

со сдвигом понял, просто в ардуиновских учебниках не нашел сего момента, а про «=!» смутило, что в учебниках последовательность другая.

скетч из примеров, шедших вместе с библиотекой, залил, но температуту почему-то кажет 85 градусов, на нагрев от руки не реагирует

датчика три штуки, проверял все.

Ладно, завтра вечером проверю подключение, может тут где накосячил. Щас мозг спит ужо.

Тут возможно магическим словом будет слово «питание» для татчика. Подлючать его так как нарисованно в стартовой статье — испытывать судьбу. Либо заработает, либо порт сгорит, либо ему не хватит питания для измерения. Вот официальный даташит на этот даташит на этот датчик http://datasheets.maxim-ic.com/en/ds/DS18B20.pdf

Схему подключения смотрите лучше в нем, а не в какой-то статье.

Схем подключения существует две. Страница 6, Figure 4 и 5.

Figure 4 это подключение «на паразитном питании». Когда необходимая энергия берется с линии данных, запасается во встроенный внутри конденсатор и «расходуется» в момент измерения. Похоже что автор той статьи и пытался использовать эту схему (и судя по скриншотам с отрицательной температурой у него тоже не получилось). Но. в момент «зарядки конденсатора» с линии данных может забиратся довольно большой ток. Что-бы «не натварить караула», производитель вносит в схему дополнительный «подпитывающий транзистор». Что-бы большой ток забирался не с пина, а все-таки из +5v. Автор статьи решил это дело «упростить». Вернее, думаю, брал где-то переводную. В англоязычных статьях тоже, почему-то, зачастую показано именно такое подключение.

Кстати не уверен, но где-то встречал что эти DS1820 бывают которые поддерживают паразитное питание, а бывают что и «нет».

Что-бы не морочится с транзюком, можно дать датчику питания «в явном виде». На третью его ногу. Это и есть Figure 5 (Внешнее Питание/ External Supply).

Подключение по этой схеме (питание заведено отдельно) и этой библиотекой лично у меня заработало «без танцев с бубном».

Источник

aaa048

0 / 0 / 0

Регистрация: 31.10.2016

Сообщений: 3

1

20.05.2017, 19:26. Показов 4617. Ответов 2

Метки нет (Все метки)


C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
#include<math.h>
#include<stdio.h>
#include<cstdlib>
#include<locale.h>
 
using namespace std;
 
void matr()
{int j; 
int f;
int k;
int i;
    cout << "vvedite razmer matr: ";
    cin >> f; // ïîëó÷åíèå îò ïîëüçîâàòåëÿ ðàçìåðà ìàññèâà
    cin >> k;
float **a = new float*[f]; // èíèöèàëèçàöèÿ ÷òî ptrarray óêàçûâàåò íà íà÷àëî ìàññèâà èç j ýëåìåíòîâ)
for ( i = 0; i < f; i++)
   a[i] = new float [k];
   for( i=0;i<f;i++)
    {
        for( k=0; k<f; k++)
            cout <<a[i][k]<<"   ";
    cout<<endl;
    }
    cout<<endl;
}
void vvod(float **a)
{int j; 
int f;
int k;
int i;
for(i=0; i<f;i++)
    {
        for(k=0; k<f; k++)
        {
         a[i][k]=rand()%10;
        }
    }
}
 
void vivod(float **a)
{int j; 
int f;
int k;
int i;
for( i=0;i<f;i++)
    {
        for( k=0; k<f; k++)
            cout <<a[i][k]<<"   ";
    cout<<endl;
    }
    cout<<endl;
}
 
int main()
{
matr();
vvod(float **a);
vivod(float **a);
 
 
    return 0;
 
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



7275 / 6220 / 2833

Регистрация: 14.04.2014

Сообщений: 26,871

20.05.2017, 20:03

2

Указатели должны быть в main(). matr() — возвращает созданный массив, или он в main() создаётся. Ну или что ты там хотел.



1



0 / 0 / 0

Регистрация: 31.10.2016

Сообщений: 3

20.05.2017, 20:18

 [ТС]

3

оке



0



  • Forum
  • Beginners
  • error: expected primary-expression befor

error: expected primary-expression before ‘float’

Hey,
I found this site because I wanted to start C++. I read half the tutorials and made a program with the info that I have. The part i screwed up on are the functions. I wrote them in but when they didn’t work I decided to not use them, but they still exist. I used one near the bottom of my code. I keeping getting the error: expected primary-expression before ‘float’ and im not sure what I am doing wrong. I probably didn’t code this in the best manner but oh well. what can I say im a noob.:) help would be greatly appreciated, and any other suggestions!
Thanks

#include <iostream>
#include <string>

using namespace std;

long operation;
float a;
float b;
float y;
float x;
float s;
float inter; // intercept
int c; // if == 1 goto
int k;
float Ia; //numerator
float Ib; //denominator
float r; //result after the ia/ib
int t; //if == 1 move on
float l;
float m;

int add (int Aa, int Ba)
{
Aa = a;
Ba = b;
int adda;
adda=Aa+Ba;
return (adda);
}
int dived (int Da, int Db)
{
Da = a;
Db = b;
int d;
d=Da/Db;
return (d);
}
int multiply (int Ma, int Mb)
{
Ma = a;
Mb = b;
int r;
r=Ma*Mb;
return (r);
}
int subtraction (float Sa, float Sb)
{
Sa = l;
Sb = m;
int s;
s=Sa-Sb;
return (s);
}
//int figure (int Ic, int Id)
//{
//cout << «What is the numerator?»;
//cin >> Ic;
//cout << «What is the denominator?»;
//cin >> Id;
//s = Ic/Id;
//return(s);
//}
int main ()
{
start:
cout << «What operation do you want? n 1 = Addition n 2 = Subtraction n 3 = Division n 4 = Multiplaction n 5 = Y=mx+b n 6 = Quit n»;
cin >> operation;
if (operation==1)
{
cout << «You have two numbers. n»;
cout << «What should number one be? n»;
cin >> a;
cout << «What should number two be? n»;
cin >> b;
cout << a+b << «n»;
c = 1;
if (c==1) goto start;

}
if (operation==2)
{ cout << «You have two numbers. n»;
cout << «What should number one be? n»;
cin >> a;
cout << «What should number two be? n»;
cin >> b;
cout << a-b << «n»;
c = 1;
if (c==1) goto start;
}
if (operation==3)
{
cout << «You have two numbers. n»;
cout << «What should number one be? n»;
cin >> a;
cout << «What should number two be? n»;
cin >> b;
cout << a/b << «n»;
c = 1;
if (c==1) goto start;
}
if (operation==4)
{
cout << «You have two numbers. n»;
cout << «What should number one be? n»;
cin >> a;
cout << «What should number two be? n»;
cin >> b;
cout << a*b << «n»;
c = 1;
if (c==1) goto start;
}
if (operation==5) {
cout << «Enter value of X n»;
cin >> x;
cout << «What is the equation? n Enter the slope not in fraction form! Need help with a decimal/full number? n Press 1 if not press any number key. n»;
cin >> k;
if (k!=1) {
goto intercept;
}
if (k==1) {
cout << «What is the numerator?»;
cin >> Ia;
cout << «What is the denominator?»;
cin >> Ib;
r = Ia/Ib;
cout << r;
goto intercept;

}
intercept:
cout << «n Please enter the slope.»;
cin >> s;
cout << «n What is the y-intercept?»;
cin >> inter;
y = s*x+inter;
cout << «n Y=» << s << «*» << x << «+» << inter << » n Y is equal to » << y ;
cout << «n Are you ready to move on? n Press 1 when ready.»;
cin >> t;
if (t==1) {
c=1;
}
if (c==1) {
goto start;
}

}
if (operation==6) {
return 0;
}
if (operation==7) {
cout << «Pick the first number.»;
cin >> l;
cout << «Pick the second number.»;
cin >> m;
cout << subtraction ( float Sa, float Sb); // This is where im getting expected primary-expression before ‘float’
}
}

That is not how you call a function.
http://cplusplus.com/doc/tutorial/functions/

Other things I noticed:
— Your variable names are not very descriptive
— You use the goto keyword in cases where it is not necessary (generally use a loop instead)
— You use several magic numbers
— Your functions create many temporary variables for no reason

Thanks! Yea I wasn’t really sure what I was doing I was just kind of messing around. Thanks for the tips. What are magic numbers?

http://en.wikipedia.org/wiki/Magic_number_%28programming%29
Basically, you are putting constants in the code with no meaning attached to them. For example, 7 could mean anything, but you have arbitrarily assigned it to subtraction. Make a constant that stores the value 7, giving it a descriptive name.

Im sorry, Im really not getting this function thing. When you call a function do you just type in the function name followed with the int’s? Iv read the functions tutorial over and over, but somehow im not understanding.

The syntax for calling a function is this:
function_name(paramter1, paramter2)
For example, to call the subtraction function with parameters «l» and «m» as I think you were intending to do, you write:
subtraction(l, m)

Thank you! I fixed that error, however I received another one, which was too many arguments to function.
(btw thank you so much for helping a helpless noob)

That error is pretty self-explanatory. You are passing more arguments to function than it can accept. For example: subtraction(a, b, c, d) would give this error because you are passing 4 arguments when the function has been defined to only take 2.

Thank you soooooo much for helping me make me little fail calculator app.!

Topic archived. No new replies allowed.

How to fix expected primary expression beforeThe expected primary expression before occurs due to syntax errors. It usually has a character or a keyword at the end that clarifies the cause. Here you’ll get access to the most common syntax mistakes that throw the same error.

Continue reading to see where you might be getting wrong and how you can solve the issue.

Contents

  • Why Does the Expected Primary Expression Before Occur?
    • – You Are Specifying the Data Type With Function Argument
    • – The Wrong Type of Arguments
    • – Issue With the Curly Braces Resulting in Expected Primary Expression Before }
    • – The Parenthesis Following the If Statement Don’t Contain an Expression
  • How To Fix the Given Error?
    • – Remove the Data Type That Precedes the Function Argument
    • – Pass the Arguments of the Expected Data Type
    • – Ensure The Equal Number of Opening and Closing Curly Brackets
    • – Add an Expression in the If Statement Parenthesis
  • FAQ
    • – What Does It Mean When the Error Says “Expected Primary Expression Before Int” in C?
    • – What Is a Primary Expression in C Language?
    • – What Are the Types of Expressions?
  • Conclusion

Why Does the Expected Primary Expression Before Occur?

The expected primary expression before error occurs when your code doesn’t follow the correct syntax. The mistakes pointed out below are the ones that often take place when you are new to programming. However, a programmer in hurry might make the same mistakes.

So, here you go:

– You Are Specifying the Data Type With Function Argument

If your function call contains the data type along with the argument, then you’ll get an error.

Here is the problematic function call:

int addFunction(int num1, int num2)
{
int sum;
sum = num1 + num2;
return sum;
}
int main()
{
int result = addFunction(int 20, int 30);
}

– The Wrong Type of Arguments

Passing the wrong types of arguments can result in the same error. You can not pass a string to a function that accepts an argument of int data type.

int main()
{
int result = addFunction(string “cat”, string “kitten”);
}

– Issue With the Curly Braces Resulting in Expected Primary Expression Before }

Missing a curly bracket or adding an extra curly bracket usually results in the mentioned error.

– The Parenthesis Following the If Statement Don’t Contain an Expression

If the parenthesis in front of the if statement doesn’t contain an expression or the result of an expression, then the code won’t run properly. Consequently, you’ll get the stated error.

How To Fix the Given Error?

You can fix the “expected primary-expression before” error by using the solutions given below:

– Remove the Data Type That Precedes the Function Argument

Remove the data type from the parenthesis while calling a function to solve the error. Here is the correct way to call a function:

int main()
{
int result = addFunction(30, 90);
}

– Pass the Arguments of the Expected Data Type

Double-check the function definition and pass the arguments of the type that matches the data type of the parameters. It will ensure that you pass the correct arguments and kick away the error.

– Ensure The Equal Number of Opening and Closing Curly Brackets

Your program must contain an equal number of opening and closing curly brackets. Begin with carefully observing your code to see where you are doing the mistake.

– Add an Expression in the If Statement Parenthesis

The data inside the parenthesis following the if statement should be either an expression or the result of an expression. Even adding either true or false will solve the issue and eliminate the error.

FAQ

You can view latest topics and suggested topics that’ll help you as a new programmer.

– What Does It Mean When the Error Says “Expected Primary Expression Before Int” in C?

The “expected primary expression before int” error means that you are trying to declare a variable of int data type in the wrong location. It mostly happens when you forget to terminate the previous statement and proceed with declaring another variable.

– What Is a Primary Expression in C Language?

A primary expression is the basic element of a complex expression. The identifiers, literals, constants, names, etc are considered primary expressions in the C programming language.

– What Are the Types of Expressions?

The different types of expressions include arithmetic, character, and logical or relational expressions. An arithmetic expression returns an arithmetic value. A character expression gives back a character value. Similarly, a logical value will be the output of a logical or relational expression.

Conclusion

The above error revolves around syntax mistakes and can be solved easily with a little code investigation. The noteworthy points depicting the solutions have been written below to help you out in removing the error:

  • Never mention the data type of parameters while calling a function
  • Ensure that you pass the correct type of arguments to the given function
  • You should not miss a curly bracket or add an extra one
  • The if statement should always be used with the expressions, expression results, true, or false

What is expected primary expression before errorThe more you learn the syntax and practice coding, the more easily you’ll be able to solve the error.

  • Author
  • Recent Posts

Position is Everything

Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.

Position is Everything

Это домашнее задание, поэтому я не хочу, чтобы вы полностью написали недостающий код. Но мне нужен довольно сильный толчок, потому что я новичок и мне нужно ознакомиться с тем, что я делаю.

Этот формат используется в AddDetailsblablablafunction ()

#define REPLNEFORMT3 "       %-7s%7f%4fn"

Линия 51 является прототипом функции

51 void AddDetailToAccumulators(float *totpayrate, *float p);/

Строка 85 находится в главном модуле и вызывает функцию AddDetailToAccumulators ()

 85 AddDetailToAccumulators(float *totpayrate, *float p);

171 void AddDetailToAccumulators(float *totpayrate, float *p)//3.6
172 {
173 totpayrate = p + totpayrate;
174 }
175 void PrintSummaryReport(float totpayrate, FILE * reportfile)/*, float  totreg, float *totovt, float totg, float totfed,
176 float totstate, float totssi, float totnet,
177 int numemps, FILE *reportfile)//3.7*/
178
179 {
180 fprintf(stdout,REPLNEFORMT3,totpayrate);
181 fprintf(reportfile,REPLNEFORMT3,totpayrate);
182}

Ошибки компилятора перечислены следующим образом:

g++ -Wall -o "main" "main.cpp" (in directory: /media/dylan07/541C-D0D8)
main.cpp:51:49: error: expected identifier before ‘*’ token
void AddDetailToAccumulators(float *totpayrate, *float p);//, //float *totp, float reg, float *totreg,
^
main.cpp:51:50: error: expected ‘,’ or ‘...’ before ‘float’
void AddDetailToAccumulators(float *totpayrate, *float p);//, //float *totp, float reg, float *totreg,
^
main.cpp: In function ‘int main()’:
main.cpp:85:29: error: expected primary-expression before ‘float’
AddDetailToAccumulators(float *totpayrate, *float p);
^
main.cpp:85:49: error: expected primary-expression before ‘float’
AddDetailToAccumulators(float *totpayrate, *float p);
^
main.cpp: In function ‘void AddDetailToAccumulators(float*, float*)’:
main.cpp:173:19: error: invalid operands of types ‘float*’ and ‘float*’ to binary ‘operator+’
totpayrate = p + totpayrate;
^
main.cpp: In function ‘void PrintSummaryReport(float, FILE*)’:
main.cpp:180:40: warning: format ‘%s’ expects argument of type ‘char*’, but argument 3 has type ‘double’ [-Wformat=]
fprintf(stdout,REPLNEFORMT3,totpayrate);
^
main.cpp:180:40: warning: format ‘%f’ expects a matching ‘double’ argument [-Wformat=]
main.cpp:180:40: warning: format ‘%f’ expects a matching ‘double’ argument [-Wformat=]
main.cpp:181:44: warning: format ‘%s’ expects argument of type ‘char*’, but argument 3 has type ‘double’ [-Wformat=]
fprintf(reportfile,REPLNEFORMT3,totpayrate);
^
main.cpp:181:44: warning: format ‘%f’ expects a matching ‘double’ argument [-Wformat=]
main.cpp:181:44: warning: format ‘%f’ expects a matching ‘double’ argument [-Wformat=]
Compilation failed.

Я надеюсь, что мое форматирование хорошо. 🙂

РЕДАКТИРОВАТЬ: BurningLights, я люблю тебя!

1

Решение

Итак, вот почему вы получаете свои ошибки.

Для первой и второй ошибки ваш *float должно быть float *, дела *float ничего не значит для компилятора и поэтому выдает ошибку. дела float * с другой стороны, сообщает компилятору, что вы хотите указатель на число с плавающей точкой, и это совершенно правильно.

Что касается третьей и четвертой ошибок, вы допустили ошибку при включении типов в вызов функции. Не делай этого! Это генерирует ошибку. Просто удалите типы так, чтобы это выглядело как AddDetailToAccumulators(totpayrate, p); и это исправит ваши ошибки, если допустить, что totpayrate и p являются указателями на числа с плавающей точкой, определенные в вашей основной функции.

Для пятой ошибки вы пытаетесь добавить два указателя вместе. Это не работает! Я предполагаю, что вы пытаетесь использовать указанные значения, поэтому вам нужно добавить оператор разыменования (*), чтобы он выглядел следующим образом: *totpayrate = *p + *totpayrate;,

Для шестой ошибки и предупреждений, ваша строка формата " %-7s%7f%4fn" говорит fprintf() что он должен ожидать строковый аргумент, а затем два аргумента float / double, чтобы иметь возможность выписать в выходной поток в указанном формате. Однако вы продолжаете указывать только один аргумент с плавающей точкой. Я не могу точно сказать вам, как это исправить, так как я не знаю намерения строки формата или то, что вы должны печатать. Я могу вам сказать, что вам нужно либо изменить строку формата, чтобы ей требовалось только одно значение с плавающей точкой, но не строку, или добавить дополнительные параметры в ваш файл. PrintSummaryReport() функция, чтобы вы могли дать fprintf() что ваша строка формата говорит о том, что она должна ожидать.

4

Другие решения

В строке 51 компилятор сообщает вам, что используется оператор косвенного обращения (*), но у вас нет объявления типа перед ним, поэтому перейдите на float * p.

В строке 173 сообщается, что вы не указали достаточно аргументов формата для строки REPLNEFORMT3, она ожидает 3, но вы дали только один.

0

For a larger sketch, I have separated a chunk of code in a separate .cpp file

#include "msg.h"
#include <Arduino.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>

void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv)
{


    String json = payload;

    // Serial.println(json); // enable to debug

    StaticJsonDocument<128> filter;

    JsonObject filter_current = filter.createNestedObject("current");
    filter_current["temp_c"] = true;
    filter_current["wind_mph"] = true;
    filter_current["pressure_mb"] = true;
    filter_current["precip_in"] = true;
    filter_current["humidity"] = true;
    filter_current["feelslike_c"] = true;
    filter_current["uv"] = true;

    StaticJsonDocument<256> doc;

    // Deseriliaze and display error description if there is any
    DeserializationError error = deserializeJson(doc, json, DeserializationOption::Filter(filter));

    if (error)
    {
        Serial.print("deserializeJson() failed: ");
        Serial.println(error.c_str());
        return;
    }

    JsonObject current = doc["current"];
    temp = current["temp_c"];          // 80
    wind = current["wind_mph"];        // 5.6
    pressure = current["pressure_mb"]; // 1005
    humid = current["humidity"];       // 93
    feel = current["feelslike_c"];     // 6.9
    uv = current["uv"];                // 1
}

together with its header file as below:

#ifndef MSG_H
#define MSG_H

void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);

#endif

I have included all the relevant libraries in the .cpp files. However, when I try to compile the code I get multiple errors such as

In file included from src/weatherapi.cpp:1:0:
include/weatherapi.h:4:17: error: variable or field 'getRequest' declared void
 void getRequest(String &payload);
                 ^
include/weatherapi.h:4:17: error: 'String' was not declared in this scope
include/weatherapi.h:4:25: error: 'payload' was not declared in this scope
 void getRequest(String &payload);
                         ^
Archiving .piobuildlolin32liba47libPubSubClient.a
In file included from src/msg.cpp:1:0:
include/msg.h:4:20: error: variable or field 'parseResponse' declared void
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);
                    ^
include/msg.h:4:20: error: 'String' was not declared in this scope
include/msg.h:4:28: error: 'payload' was not declared in this scope
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);
                            ^
include/msg.h:4:37: error: expected primary-expression before 'float'
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);
                                     ^
include/msg.h:4:50: error: expected primary-expression before 'float'
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);
                                                  ^
include/msg.h:4:63: error: expected primary-expression before 'int'
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);
                                                               ^
include/msg.h:4:78: error: expected primary-expression before 'int'
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);
                                                                              ^
include/msg.h:4:90: error: expected primary-expression before 'float'
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);
                                                                                          ^
include/msg.h:4:103: error: expected primary-expression before 'int'
 void parseResponse(String &payload, float &temp, float &wind, int &pressure, int &humid, float &feel, int &uv);

The function parseResponse doesn’t return anything so I don’t know why it’s complaining about being declared as void. Same is true for the function getRequest. Also, is there something wrong in the function prototype as I am passing references?

Edit: Here is the weatherapi.cpp & .h file

#include "weatherapi.h"
#include <HTTPClient.h>
#include <Arduino.h>

const char url[] = "http://api.weatherapi.com/v1/current.json?key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

void getRequest(String &payload)
{

     HTTPClient getClient;

    getClient.begin(url);

   
    int httpCode = getClient.GET();

    //get response and check HTTP status code returned
    if (httpCode > 0)
    {
        payload = getClient.getString();
        Serial.print("HTTP Status: ");
        Serial.println(httpCode);
    }
    else
    {
        Serial.println("Error on HTTP request");
    }
   
    getClient.end();
} 

weatherapi.h file

#ifndef WEATHERAPI_H
#define WEATHERAPI_H

void getRequest(String &payload);
#endif

                                                                                             

Why do I get that error message from this? What am I doing wrong?

#include <iomanip>
#include <iostream>
#include <cmath>
using namespace std;

void printDescription();
void computePaycheck(float, int, float&, float&);
int main()
{    
cout << setprecision(2) << fixed;

cout<< "Welcome to the Pay Roll Program" << endl;

printDescription(); 
   
computePaycheck(float payRate, int hours, float grossPay, float netPay);
    
cout <<"We hope you enjoyed this program" <<endl;
   
system("PAUSE");
return EXIT_SUCCESS;
}
void printDescription()
{
cout <<"This program will find your gross pay and net pay"<< endl;    
}

void computePaycheck(float, int, float&, float&)
{
float payRate;
float grossPay;
float netPay;
int hours;
   cout <<"Please input the pay to hours" << endl;
cin >> payRate;
cout << endl << endl;
  
cout <<"Please input the number of hours worked" << endl;
cin >> hours;
cout << endl << endl;

cout <<"The gross pay is $"<< grossPay << endl;

cout <<"The net pay is $" <<netPay<< endl;

grossPay = (payRate) * (hours);

netPay = (grossPay) - (grossPay * 0.15);    
}  

The error is at this line

computePaycheck(float payRate, int hours, float grossPay, float netPay);

Понравилась статья? Поделить с друзьями:
  • Error expected primary expression before const
  • Error expect received toequal expected deep equality
  • Error expected primary expression before char
  • Error exp was not declared in this scope
  • Error exiting jvm with code 1 org apache zookeeper util serviceutils