Error expected initializer before float

Как исправить [Error] expected initializer before 'bool'? C++ Решение и ответ на вопрос 1745001

EvGENJho

0 / 0 / 0

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

Сообщений: 20

1

25.05.2016, 13:28. Показов 6671. Ответов 4

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


C++
1
2
3
4
5
6
7
8
9
#include <string.h>
#include <cstring>
 
int main()
   bool exists = false;
for (int i = 0; i < strlen(str)-1 && !exists; i++)
     if ((str[i] == 'a' && str[i+1] == 'b' ||
         (str[i] == 'b' && str[i+1] == 'a')) 
          exists = true;

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



0



385 / 279 / 478

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

Сообщений: 769

25.05.2016, 13:32

2

main должна быть в фигурных скобках. кроме того, у вас str не объявлено и не проинициализировано.



0



0 / 0 / 0

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

Сообщений: 20

25.05.2016, 13:42

 [ТС]

3

1. Дана строка символов. Выяснить имеется ли в строке следующие два символа стоящие рядом.

2. Дан текст. Напечатать те слова, которые удовлетворяют следующему свойству: буквы слова упорядоченны по алфавиту.

Помогите пожалуйста написать программы.



0



nmcf

7275 / 6220 / 2833

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

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

25.05.2016, 15:09

4

Сказали же скобки добавить.

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <cstring>
 
using namespace std;
 
int main()
{
char s[100];
bool exists = false;
 
cin.getline(s, 100);
 
for (int i = 0; i < strlen(str)-1 && !exists; i++)
  if ((str[i] == 'a' && str[i+1] == 'b' || (str[i] == 'b' && str[i+1] == 'a'))
    exists = true;
 
cout << (exists ? "Yes." : "No.") << endl;
 
}



0



0 / 0 / 0

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

Сообщений: 20

25.05.2016, 15:24

 [ТС]

5

Благодарю

Добавлено через 51 секунду
Можете ещё со второй задачей помочь??



0



Содержание

  1. Error expected initializer before float
  2. Error expected initializer before float
  3. Error expected initializer before float
  4. Проблема компиляции прошивки

Error expected initializer before float

I’m writing a class with an array and I’m supposed to calculate the average of some entered grades outside the class and in the main but I get the error
Expected Initializer before ‘.’ token

I’m not to sure what to do or i even did the class right
Please help!

What if I promised you $1000, but then just walk away, leaving you empty handed?
You make a promise on line 24, but you don’t keep it.

The error is on line 44. Please explain this code:
float gradeAverage.getGrade();

Line 44 looks like a nice prototype, but what is it doing in the middle of the program?

In the function «getGrade()» Why are you printing the array when you should be returning something from the array. In this case the «getGrade()» function should have a parameter the represents the element of the array that you need.

As you have it «float getGrade ()» would be better named «void printGrades ()».

Hope that helps,

I know that i shouldn’t be printing the there but the question was my teacher gave me was this
Write a class called Student that contains a property called grades that can store a
maximum of 10 grades. Create a setter and a getter method. The setter method
will take no parameters and return no parameters. Instead, within the setter
method you must construct a loop that will ask the user to enter 10 grades. The
getter method will simply print the 10 grades; so, it will take no and return no
parameters. Yes, that is a misnomer; this is because passing and returning arrays
has not been covered yet. Create another method called computeAverage that
return the average of all the grades. Create another method called
minimumGrade that returns the minimum grade the student received.

He knows it’s a misnomer but he wants us to do it anyway.
He hasn’t covered it yet so I was just looking it up but nothing I find helps

Now that I see what is required I will take a look tomorrow and see what I can do.

Источник

Error expected initializer 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 initializer before float

prog3.cpp:10:1: error: expected initializer before ‘int’
int main ()
^
this is what i get when i run this program please any help regarding this it will be much appreciated and please tell me if i made this program workable like with boolean expression if the function and prototype are well declared and performing together

/*This program ask user to input Hour, Minute and seconds and if the user
put in the valid format it runs othervise it says error. */

bool readTime(int &hours, int &minutes, int &seconds)

int main ()
<
int h,m,s;
if(readTime(h,m,s)) <
printf(«%2d:%2d:%2d» h, m, s);
return 0;
>
>

printf(«please enter time in format 09:30:50n»);
int count = scanf(«%2d:%2d:%2d», &hh, &mm, &ss);
>
// did they get the right format?
if (count !=3) <
printf(«Invalid formatn»);
return false;
>
// is the number of hours correct?
if ((hh 23)) <
printf(«Invalid hour %d n», hh);
return false;
>
//is number of minutes wrong?
if ((mm 0)) <
printf(«Invalid Minutes %d n», mm);
return false;
>
//is number of seconds wrong?
if ((ss 0)) <
printf(«Invalid seconds %d n», mm);
return false;
>

now this is what i get after doing your instructions

prog3.cpp: In function ‘int main()’:
prog3.cpp:14:28: error: expected ‘)’ before ‘h’
printf(«%2d:%2d:%2d» h, m, s);
^
prog3.cpp:14:35: warning: format ‘%d’ expects a matching ‘int’ argument [-Wformat=]
printf(«%2d:%2d:%2d» h, m, s);
^
prog3.cpp: In function ‘bool readTime(int&, int&, int&)’:
prog3.cpp:24:8: warning: unused variable ‘count’ [-Wunused-variable]
int count = scanf(«%2d:%2d:%2d», &hh, &mm, &ss);
^
prog3.cpp:25:4: warning: no return statement in function returning non-void [-Wreturn-type]
>
^
prog3.cpp: At global scope:
prog3.cpp:27:4: error: expected unqualified-id before ‘if’
if (count !=3) <
^
prog3.cpp:32:4: error: expected unqualified-id before ‘if’
if ((hh 23)) <
^
prog3.cpp:37:4: error: expected unqualified-id before ‘if’
if ((mm 0)) <
^
prog3.cpp:42:4: error: expected unqualified-id before ‘if’
if ((ss 0)) <
^
prog3.cpp:47:1: error: expected declaration before ‘>’ token
>
^

You have extra braces.

You will find it extremely helpful to
1. Indent your code consistently. Use an editor which does this for you.
2. Type the closing brace at the same type you type the opening brace. Use an editor which does this for you.

Here is a «fixed» version. (there’s still some issues, but it will compile with warnings.)

i run your program but then i see this issue it will be helpful if i get perfectly running program so that i know for my upcoming exam how to make this type of program run. I am currently preparing for my exam. hope to see some help from you guys out there

In function ‘int main()’:
9:26: error: expected ‘)’ before ‘h’
9:33: warning: format ‘%d’ expects a matching ‘int’ argument [-Wformat=]
In function ‘bool readTime(int&, int&, int&)’:
41:1: warning: control reaches end of non-void function [-Wreturn-type]

This line :
printf( «%2d:%2d:%2d» h, m, s);

Should be :
printf( «%2d:%2d:%2d» , h, m, s); // An extra comma (,)

thank you for the help but why am i facing problem like this?

progs3.cpp:41:1: warning: control reaches end of non-void function [-Wreturn-type]
>
^

Notice that the compiler provides you with the location of any errors that it encounters.

Line 9, column 26 — usually there’s a filename, too. There’s a missing comma (I missed it, apologies.)

If the problem is a syntax error, the compiler will report the error no earlier than it appears. Look at the location of the first error and then look backwards towards the beginning of the file until you find it.

thank you for the help its so much appreciated and helpful for my upcoming exam and future programming errors. but can you help me with my issue on line 41?

Источник

Проблема компиляции прошивки

Здравствуйте уважаемые гуру 3dtoday. Прошу Вас помощи. Собираю свой первый 3D принтер Prusa i3

-MEGA2560(в диспетчере определяется CH340)

-DRV8825(перемычки установлены в 1/16)

Собственно проблема в залитии первой прошивки Марлин 1.1.9

Arduino: 1.0.6 (Windows 7), Board: «Arduino Mega 2560 or Mega ADK»

C:Program FilesArduinohardwaretoolsavrbinavr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega2560 -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106 -IC:Program FilesArduinohardwarearduinocoresarduino -IC:Program FilesArduinohardwarearduinovariantsmega C:Users1AppDataLocalTempbuild474787399719840586.tmpblinkm.cpp -o C:Users1AppDataLocalTempbuild474787399719840586.tmpblinkm.cpp.o

In file included from /MarlinConfig.h:27,

/macros.h:183: warning: identifier ‘decltype’ will become a keyword in C++0x

In file included from /MarlinConfig.h:42,

/SanityCheck.h:36:4: error: #error «Marlin requires C++11 support (gcc >= 4.7, Arduino IDE >= 1.6.8). Please upgrade your toolchain.»

In file included from /MarlinConfig.h:42,

/SanityCheck.h:378: warning: identifier ‘static_assert’ will become a keyword in C++0x

In file included from /MarlinConfig.h:27,

macros.h:183: error: expected initializer before ‘auto’

macros.h:186: error: expected initializer before ‘auto’

macros.h:189: error: expected initializer before ‘const’

fastio.h:112: error: use of enum ‘WaveGenMode’ without previous declaration

fastio.h:112: error: expected unqualified-id before ‘:’ token

fastio.h:132: error: use of enum ‘CompareMode’ without previous declaration

fastio.h:132: error: expected unqualified-id before ‘:’ token

fastio.h:140: error: use of enum ‘ClockSource’ without previous declaration

fastio.h:140: error: expected unqualified-id before ‘:’ token

fastio.h:152: error: use of enum ‘ClockSource2’ without previous declaration

fastio.h:152: error: expected unqualified-id before ‘:’ token

In file included from /MarlinConfig.h:39,

/HAL.h: In function ‘void HAL_timer_start(uint8_t, uint32_t)’:

HAL.h:121: error: ‘WGM_CTC_OCRnA’ was not declared in this scope

HAL.h:124: error: ‘COM_NORMAL’ was not declared in this scope

HAL.h:131: error: ‘CS_PRESCALER_8’ was not declared in this scope

In file included from /MarlinConfig.h:42,

SanityCheck.h:378: error: expected constructor, destructor, or type conversion before ‘(‘ token

SanityCheck.h:1599: error: expected constructor, destructor, or type conversion before ‘float’

SanityCheck.h:1599: error: expected unqualified-id before ‘,’ token

SanityCheck.h:1600: error: expected constructor, destructor, or type conversion before ‘=’ token

SanityCheck.h:1600: error: expected unqualified-id before ‘,’ token

SanityCheck.h:1601: error: expected constructor, destructor, or type conversion before ‘=’ token

SanityCheck.h:1603: error: expected constructor, destructor, or type conversion before ‘(‘ token

SanityCheck.h:1604: error: expected constructor, destructor, or type conversion before ‘(‘ token

SanityCheck.h:1605: error: expected constructor, destructor, or type conversion before ‘(‘ token

SanityCheck.h:1606: error: expected constructor, destructor, or type conversion before ‘(‘ token

SanityCheck.h:1607: error: expected constructor, destructor, or type conversion before ‘(‘ token

SanityCheck.h:1608: error: expected constructor, destructor, or type conversion before ‘(‘ token

In file included from /MarlinConfig.h:43,

enum.h:35: error: use of enum ‘AxisEnum’ without previous declaration

enum.h:35: error: expected unqualified-id before ‘:’ token

enum.h:82: error: use of enum ‘DebugFlags’ without previous declaration

enum.h:82: error: expected unqualified-id before ‘:’ token

enum.h:131: error: use of enum ‘MarlinBusyState’ without previous declaration

enum.h:131: error: expected unqualified-id before ‘:’ token

enum.h:143: error: use of enum ‘LsAction’ without previous declaration

enum.h:143: error: expected unqualified-id before ‘:’ token

enum.h:148: error: use of enum ‘LCDViewAction’ without previous declaration

enum.h:148: error: expected unqualified-id before ‘:’ token

Windows7 64 (также пробовал на 32 ничего не пошло) Со всевозможными изменениями настроек портов и их скорости.

Перепробовал много разных марлин`новских прошивок в каждой свои проблемы.

Источник

  • Forum
  • Beginners
  • Help please!

Help please!

Can someone please help me? I recently started «advanced» c++.
Can someone help me with my problem?
Expected initializer before ‘float’
can you fix the problem? or tell me hwo to fix it

#include <windows.h>
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
float veritces;
float vertices[] = {
0.0f, 0.5f, // Vertex 1 (X, Y)
0.5f, -0.5f, // Vertex 2 (X, Y)
-0.5f, -0.5f // Vertex 3 (X, Y)
};

Last edited on

different data types with same ID? this is not possible in C++.

Aceix.

If that is the exact code you are missing curly braces around Main

I may be taking this the wrong way, but either it is a prototype or a function/method header:

1
2
3
4
5
6
7
8
9
10
#include <windows.h>
int APIENTRY WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow)
{//This Was Missing?
    float veritces;
    float vertices[] = {
        0.0f, 0.5f, // Vertex 1 (X, Y)
        0.5f, -0.5f, // Vertex 2 (X, Y)
        -0.5f, -0.5f // Vertex 3 (X, Y)
    };
}//This Was Missing? 

My bet’s on header of a function.

Last edited on

Topic archived. No new replies allowed.

  • Печать

Страницы: [1]   Вниз

Тема: помогите с программой  (Прочитано 2899 раз)

0 Пользователей и 1 Гость просматривают эту тему.

Оффлайн
Sharabdin

при запусске этой программы

#include <iostream>
#include <iomanip>

#include <iostream>

#include <math.h>
#include <unistd.h>
#define T (24*60*30ul)      //Период Моделирования
#define Cmax 100            //Максимальное число одновременных подключений
#define RON discrete uniform() //Длительность Подключений
#define RIN uniform (1,10)  //Интервал Времени Между подключениями
#define RPT uniform (100,1000)  //Энергопотребления Подключения
#define C (125*125*125*125*5)
#define tax (8.0/10)
using namespace std;
/*====================================*/

float rand(void)
{
 static unsigned long int u=C;

 u*=C;

 return float (u)/0xFFFFFFFF;
}

/*====================================*/
float discrete (void)

 float x[8]={20,40,60,100};
 float P[8]={0 ,1; 0,2;0,3; 0,4},S,r;
 int k=0;
 S=P[0];
 r=rand();
  while (S<=r)
 {
   k++;
   S+=P[k];
 }
 return x[k];
}

/*====================================*/

float gauss (float m,float sigma)
{
return sqrt(-2*log(rand()))*sin(2*M_PI*rand())*sigma+m;
}

/*====================================*/
float uniform (float a, float b)
{
return rand()*(b-a)+a;
}
/*====================================*/
int main (void)
{

   unsigned long int i,j,l,nEvent,ton[Cmax],tin,nOtkaz,t_on;
  float nagr, pot[Cmax],nPotrTotal,potr,MinEnergiya,MaxEnergiya;;                           // Инициализация

  nEvent=0; nPotrTotal=0; nOtkaz=0; t_on=0; potr=0;
  for(i=0;i<Cmax;i++) { ton[i]=-1; pot[i]=0; }
  MinEnergiya=ULONG_MAX,MaxEnergiya=0;

  tin=RIN;

  // Основной Цыкл
  for(i=0;i<T;i++)
  {
     // Обработка
     for(j=0;j<Cmax;j++) if(ton[j]==i)
     {
       nEvent++;
       ton[j]=-1;

     }

     // Обработка очередного входного сообщения

     if(i==tin)
     {
  j=0; while((ton[j]!=-1) && (j<Cmax)) j++;
  if(j!=Cmax)
  {
      t_on=RON;
      ton[j]=t_on+i;

      potr=RPT;
      nPotrTotal+=potr*t_on/60;

      pot[j]=potr;

      // Определения Пиковой и Минимальной нагрузки
      nagr=0;
      for(l=0;l<Cmax;l++) nagr+=pot[l];

      if(nagr>MaxEnergiya)  MaxEnergiya=nagr;
      if(nagr<MinEnergiya)  MinEnergiya=nagr;

  } else nOtkaz++;

  tin=RIN+i;
      }
   }

   std::cout<<"........................ Rezultati modelirovaniya ..............................";
   std::cout<<"Obshiy ob'em potrebleniya energii za period modelirovaniya:"<<nPotrTotal/1000<<" kVt"<<std::endl;
   std::cout<<"2. Obshiy ob'em potrebleniya energii za period modelirovaniya n   v stoimostnom viragenii :  "<<nPotrTotal/1000*tax<<" rub"<<std::endl;
   std::cout<<"3. Chislo obrabotannih trebovaniy: "<<nEvent<<std::endl;
   std::cout<<"4. Chislo otkazov: "<<nOtkaz<<std::endl;
   std::cout<<"5. Pikovaya nagruzka v sisteme:  "<<MaxEnergiya/1000<<" kVt"<<std::endl;
   std::cout<<"6. Minimalnaya nagruzka v sisteme:  "<<MinEnergiya<<" Vt"<<std::endl;
   //getch() переход;
}

выходят такие ошибки

3.cpp:29: ошибка: expected initializer before ‘float’
3.cpp:30: ошибка: expected `}' before ‘;’ token
3.cpp:30: ошибка: expected unqualified-id before numeric constant
3.cpp:30: ошибка: expected unqualified-id before numeric constant
3.cpp:30: ошибка: expected unqualified-id before numeric constant
3.cpp:30: ошибка: expected declaration before ‘}’ token

« Последнее редактирование: 29 Января 2009, 12:42:05 от Sharabdin »


burgua

1
#include <iostream> дважды?
2.

float discrete (void)

 float x[8]={20,40,6

Кто будет { ставить?
3
Дабы избежать таких ошибок, используй IDE.

4.
Для кода есть тэг code, делает текст на порядок читабельнее.

« Последнее редактирование: 29 Января 2009, 12:23:32 от burgua »


Оффлайн
Sharabdin

не понял? что такое ide я новичек и в c++ тоже плохо соображая объясните пожалуйста


burgua

« Последнее редактирование: 29 Января 2009, 12:29:09 от burgua »


Оффлайн
Sharabdin

сделал как вы сказали теперь одна ошибка

3.cpp:26: ошибка: expected initializer before ‘void’


Оффлайн
Sharabdin

вот изначальная программа я ее хотел запустить на g++ :

# include <iostream.h>
# include <math.h>
# include <conio.h>
# include <values.h>
#include <limits.h>
# define T (24*60*30ul)      //period modelirovaniya
# define Cmax 100            //max. chislo odnovr. podkl.
# define RON discrete uniform() //dlit. podkl.
# define RIN uniform (1,10)  //interval vremeni mejdu podklucheniyami
# define RPT uniform (100,1000)  //energopotreblenie podklucheniy
# define C (125*125*125*125*5)
# define tax (8.0/10)

/*====================================*/

float rand(void)
{
 static unsigned long int u=C;

 u*=C;

 return float (u)/0xFFFFFFFF;
}

/*====================================*/
float discrete (void)
{
 float x[8]={20,40,60,100};
 float P[8]={0 ,1; 0,2;0,3; 0,4},S,r;
 int k=0;
 S=P[0];
 r=rand();
  while (S<=r)
 {
   k++;
   S+=P[k];
 }
 return x[k];
}

/*====================================*/

float gauss (float m,float sigma)
{
return sqrt(-2*log(rand()))*sin(2*M_PI*rand())*sigma+m;
}

/*====================================*/
float uniform (float a, float b)
{
return rand()*(b-a)+a;
}
/*====================================*/
void main (void)
{

   unsigned long int i,j,l,nEvent,ton[Cmax],tin,nOtkaz,t_on;
  float nagr, pot[Cmax],nPotrTotal,potr,MinEnergiya,MaxEnergiya;;                           // inizializaciya

  nEvent=0; nPotrTotal=0; nOtkaz=0; t_on=0; potr=0;
  for(i=0;i<Cmax;i++) { ton[i]=-1; pot[i]=0; }
  MinEnergiya=ULONG_MAX,MaxEnergiya=0;

  tin=RIN;

  // osnovnoy cikl
  for(i=0;i<T;i++)
  {
     // obrabotka zavershenniya
     for(j=0;j<Cmax;j++) if(ton[j]==i)
     {
       nEvent++;
       ton[j]=-1;

     }

     // obrabotka ocherednogo vhod. sob

     if(i==tin)
     {
  j=0; while((ton[j]!=-1) && (j<Cmax)) j++;
  if(j!=Cmax)
  {
      t_on=RON;
      ton[j]=t_on+i;

      potr=RPT;
      nPotrTotal+=potr*t_on/60;

      pot[j]=potr;

      // opredelyaem pikovyu i minimalnyu nagruzki
      nagr=0;
      for(l=0;l<Cmax;l++) nagr+=pot[l];

      if(nagr>MaxEnergiya)  MaxEnergiya=nagr;
      if(nagr<MinEnergiya)  MinEnergiya=nagr;

  } else nOtkaz++;

  tin=RIN+i;
      }
   }

   cout<<"........................ Rezultati modelirovaniya ..............................";
   cout<<"Obshiy ob'em potrebleniya energii za period modelirovaniya:"<<nPotrTotal/1000<<" kVt"<<endl;
   cout<<"2. Obshiy ob'em potrebleniya energii za period modelirovaniya n   v stoimostnom viragenii :  "<<nPotrTotal/1000*tax<<" rub"<<endl;
   cout<<"3. Chislo obrabotannih trebovaniy: "<<nEvent<<endl;
   cout<<"4. Chislo otkazov: "<<nOtkaz<<endl;
   cout<<"5. Pikovaya nagruzka v sisteme:  "<<MaxEnergiya/1000<<" kVt"<<endl;
   cout<<"6. Minimalnaya nagruzka v sisteme:  "<<MinEnergiya<<" Vt"<<endl;
   //getch();
}


Оффлайн
Sharabdin

Это Имитационное моделирование локальной системы энергоснабжения цель одна выходные данные вывести и построить на exsel график изменений


Оффлайн
Sharabdin

программа работает на Borland C+ спасибо за помощь что нибудь надумаю)


burgua

Что за прога — это не так уж и важно.
Разберись с 92-ой строкой.
Без нее запускается.

Удачи.

P.S. А то, что написана  под Борланд и так видно.


Оффлайн
Sharabdin

92 у меня компилятор не жалуеться ведь на 92 строку ???  проблема с

/*====================================*/

float discrete (void){
 float x[8]={20,40,60,100};

« Последнее редактирование: 29 Января 2009, 13:00:47 от Sharabdin »


burgua


Оффлайн
Sharabdin


burgua

Не забудь что 92-ая строка просто закомментирована.
Утренний мозг слабо соображает, там я не разбирался.


Оффлайн
Sharabdin

Большое спасибо тебе burgua ,нечего так сойдет!:)


Оффлайн
Sharabdin

проблема была  тут

#define RON discrete uniform() //Длительность Подключений сделал так заработало видимо непонимает подключенную функцию discrete

define RON uniform(1,10)
незнаю вроде работает верно


  • Печать

Страницы: [1]   Вверх

im new here ,and new at proggraming in general .
whem im trying to run this code:

#include<fstream>
#include <iostream>
#include "main.h"
using namespace std;
int main()
{
 short arr_size ()
float temp;
point point_arr[99];
ifstream my_file   ("points.txt");
while(!my_file.eof())
{
    my_file>>temp ;
    point_arr[arr_size].set_x(temp);
    my_file>>temp ;
    point_arr[arr_size].set_y(temp);
    arr_size++;
}
arr_size--;
my_file.close();
ex_point(point_array,arr_size);
cout<<"the middle point is:("<<mid_p(point_array,arr_size).get_x()<<","<<mid_p(point_array,arr_size).get_y()<<")n";
return 0;
}

im getting this error : «error «expected initializer before ‘using'» c++»
this is the first time i get this error . it may be somthing wrong with «main.h» ?
this is «main.h » :

    #ifndef MAIN_H_INCLUDED
#define MAIN_H_INCLUDED
#include<iostream>
class point
{
    float x ,y ;
public :
    point(float a,float b){x=a;y=b;}
    point(){};
    void set_x(float a){x=a;};
    void set_y(float b){x=b;};
    const float get_x(){return x; };
    const float get_y(){return y; };
    const void show();
    const float pitagoras();
};
const point mid_p(point[],float);
const void ex_point(point[],float)



#endif // MAIN_H_INCLUDED

thank you !
ivory

Arduino IDE ошибки компиляции скетча

Ошибки компиляции Arduino IDE возникают при проверке или загрузке скетча в плату, если код программы содержит ошибки, компилятор не может найти библиотеки или переменные. На самом деле, сообщение об ошибке при загрузке скетча связано с невнимательностью самого программиста. Рассмотрим в этой статье все возможные ошибки компиляции для платы Ардуино UNO R3, NANO, MEGA и пути их решения.

Ошибка компиляции для Arduino Nano, Uno, Mega

Самые простые ошибки возникают у новичков, кто только начинает разбираться с языком программирования Ардуино и делает первые попытки загрузить скетч. Если вы не нашли решение своей проблемы в статье, то напишите свой вопрос в комментариях к этой записи и мы поможем решить вашу проблему с загрузкой (бесплатно!).

Ошибка: avrdude: stk500_recv(): programmer is not responding

Что делать в этом случае? Первым делом обратите внимание какую плату вы используете и к какому порту она подключена (смотри на скриншоте в правом нижнем углу). Необходимо сообщить Arduino IDE, какая плата используется и к какому порту она подключена. Если вы загружаете скетч в Ардуино Nano V3, но при этом в настройках указана плата Uno или Mega 2560, то вы увидите ошибку, как на скриншоте ниже.

Ошибка Ардуино: programmer is not responding

Такая же ошибка будет возникать, если вы не укажите порт к которому подключена плата (это может быть любой COM-порт, кроме COM1). В обоих случаях вы получите сообщение — плата не отвечает ( programmer is not responding ). Для исправления ошибки надо на панели инструментов Arduino IDE в меню «Сервис» выбрать нужную плату и там же, через «Сервис» → «Последовательный порт» выбрать порт «COM7».

Ошибка: a function-definition is not allowed here before ‘<‘ token

Это значит, что в скетче вы забыли где-то закрыть фигурную скобку. Синтаксические ошибки IDE тоже распространены и связаны они просто с невнимательностью. Такие проблемы легко решаются, так как Arduino IDE даст вам подсказку, стараясь отметить номер строки, где обнаружена ошибка. На скриншоте видно, что строка с ошибкой подсвечена, а в нижнем левом углу приложения указан номер строки.

Ошибка: a function-definition is not allowed here before ‘<‘ token

Ошибка: expected initializer before ‘>’ token / expected ‘;’ before ‘>’ token

Сообщение expected initializer before ‘>’ token говорит о том, что вы, наоборот где-то забыли открыть фигурную скобку. Arduino IDE даст вам подсказку, но если скетч довольно большой, то вам придется набраться терпения, чтобы найти неточность в коде. Ошибка при компиляции программы: expected ‘;’ before ‘>’ token говорит о том, что вы забыли поставить точку с запятой в конце командной строки.

Ошибка: ‘ ‘ was not declared in this scope

Что за ошибка? Arduino IDE обнаружила в скетче слова, не являющиеся служебными или не были объявлены, как переменные. Например, вы забыли продекларировать переменную или задали переменную ‘DATA’, а затем по невнимательности используете ‘DAT’, которая не была продекларирована. Ошибка was not declared in this scope возникает при появлении в скетче случайных или лишних символов.

Ошибка Ардуино: was not declared in this scope

Например, на скриншоте выделено, что программист забыл продекларировать переменную ‘x’, а также неправильно написал функцию ‘analogRead’. Такая ошибка может возникнуть, если вы забудете поставить комментарий, написали функцию с ошибкой и т.д. Все ошибки также будут подсвечены, а при нескольких ошибках в скетче, сначала будет предложено исправить первую ошибку, расположенную выше.

Ошибка: No such file or directory / exit status 1

Данная ошибка возникает, если вы подключаете в скетче библиотеку, которую не установили в папку libraries. Например, не установлена библиотека ИК приемника Ардуино: fatal error: IRremote.h: No such file or directory . Как исправить ошибку? Скачайте нужную библиотеку и распакуйте архив в папку C:Program FilesArduinolibraries. Если библиотека установлена, то попробуйте скачать и заменить библиотеку на новую.

exit status 1 Ошибка компиляции для платы Arduino Nano

Довольно часто у новичков выходит exit status 1 ошибка компиляции для платы arduino/genuino uno. Причин данного сообщения при загрузке скетча в плату Arduino Mega или Uno может быть огромное множество. Но все их легко исправить, достаточно внимательно перепроверить код программы. Если в этом обзоре вы не нашли решение своей проблемы, то напишите свой вопрос в комментариях к этой статье.

Источник

Arduino.ru

Нужна помощь

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Собирался снимать с DHT11 показатели и по i2c выводить их на LCD 2004

Собрал вот такой скетч:

3. // include the library code:

4. #include «pitches.h»

5. #include «stDHT.h»

6. DHT dht(DHT11); // Указать датчик DHT11, DHT21, DHT22

7. // Установить ЖК-адрес для 0x27 для отображения 20 символов и 4 линии

8. LiquidCrystal_I2C lcd(0x27, 20, 4);

11. // initialize the LCD

  1. // Turn on the blacklight and print a message.

16. lcd.setCursor(0, 1);

17. // настройка UART (связь с компьютером — через виртуальный COM-порт посредством USB)

19. // настройка вывода датчика DHT11

20. pinMode(6, INPUT);

21. digitalWrite(6, HIGH);

27. int t = sens.readTemperature(2); // чтение датчика на пине 6

28. int h = sens.readHumidity(2); // чтение датчика на пине 6

29. // передача данных о температуре и влажности по виртуальному COM-порту

35. Serial.println(» C «);

36. // отображение данных о температуре и влажности на знакосинтезирующем ЖКИ

  1. // set the cursor to column 0, line 0
  2. // (note: line 1 is the second row, since counting begins with 0):

39. lcd.setCursor(0, 0);

43. lcd.setCursor(0, 1);

  1. // print the number of seconds since reset:

Источник

When I try to compile the following code in Arduino ,I get the error «expected initializer before ‘void'».How can I get the code to work?

  void setup() {  
  Serial.begin(9600);
}

float area = 0.0f,pre_area = 0.0f,tarea = 0.0f,rarea = 0.0f;
int x = 0,pre_x = 0,t = 0,pre_t = 0;


long unsigned int t


void loop()
{
  x = analogRead(A0);
  t = millis();
  float diff_t = (float)(t - pre_t)/1000.0f;
  area = (0.5 * (pre_x + x) * diff_t) + pre_area;

  Serial.print(area);
  analogWrite(DAC0, area);
  pre_x = x;
  pre_area = area;
  pre_time = t;
}

asked Aug 26, 2015 at 10:40

Viphuchit Sirikhemaporn's user avatar

1

You add the semicolon that is missing at the end of long unsigned int t

answered Aug 26, 2015 at 10:47

Majenko's user avatar

1

Why have you written t = 0 here and declared it again below??

int x = 0,pre_x = 0,t = 0,pre_t = 0;

Semi Colon Missing

long unsigned int t;

Where have you declared pre_time??

  pre_time = t;

answered Aug 26, 2015 at 10:49

evolutionizer's user avatar

long unsigned int t

No semicolon.


Plus, make up your mind what type «t» is:

int x = 0,pre_x = 0,t = 0,pre_t = 0;
long unsigned int t;

Is it int or long unsigned int?


How can I get the code to work?

Avoid C++ syntax errors.

answered Aug 26, 2015 at 10:53

Nick Gammon's user avatar

Nick GammonNick Gammon

35.7k12 gold badges62 silver badges121 bronze badges

Понравилась статья? Поделить с друзьями:
  • Error expected initializer before cout
  • Error expected initializer before class
  • Error expected initializer before cin
  • Error expected initializer before char
  • Error expected indentation of 6 spaces but found 4 indent