I’m getting this error on the below code and can’t seem to see where i’m going wrong. Please could someone point me in the right direction. Thanks in advance.
**************The Error is ************************
*******In function ‘float calcActualAmount(float,int)’
Line62*expected ‘while’ before ‘(‘ token
The piece of code i’m getting the error on is:
************************************************
amountP = calcAllowedPerChild(nrChildrenP) — leftToSpend;
while (leftToSpend == 0);
}
return(amountP);
}
int main()
********************************************
#include <iostream>
using namespace std;
const float maxPerUnit = 20000.00;
//minPerChild includes a standard gift consisting of a bath towel and a facecloth
const float minPerChild = 100.00;
const float maxPerChild = 180.00;
//depending on the amount, the child may also get one or more of the following;
const float TOOTHBRUSH = 29.95;
const float HIGHLIGHTERS = 25.95;
const float CRAYONS = 17.95;
const float NOTEBOOK = 12.95;
const float PEN = 9.99;
float calcAllowedPerChild(int nrChildrenP)
{
float amtGiftP = 20000.00 / nrChildrenP;
return amtGiftP;
}
float calcActualAmount(float amountP, int nrChildrenP)
{
float leftToSpend;
if (calcAllowedPerChild(nrChildrenP) > 180)
amountP = 180;
else if (calcAllowedPerChild(nrChildrenP) < 180)
leftToSpend = calcAllowedPerChild(nrChildrenP) — 100;
do
{
for (int i = 1; i <= 5; i++)
switch (i)
{
case 1: leftToSpend -= TOOTHBRUSH;
break;
case 2: leftToSpend -= HIGHLIGHTERS;
break;
case 3: leftToSpend -= CRAYONS;
break;
case 4: leftToSpend -= NOTEBOOK;
break;
case 5: leftToSpend -= PEN;
break;
}
amountP = calcAllowedPerChild(nrChildrenP) — leftToSpend;
while (leftToSpend == 0);
}
return(amountP);
}
int main()
{
float amtGift; // Allowed amount per child
float amtSpentPerChild = 0.00; // actual amount spent per child
float totalSpent = 0.00; // total spent for 1 orphanage
float totalAll = 0.00; // total spent for all 4 orphanages
int nrChildren;
cout << «Enter the amount of children: » << endl;
cin >> nrChildren;
amtGift = calcAllowedPerChild(nrChildren);
cout.setf(ios::fixed);
cout.precision(2);
cout << endl << » Allowable amount per child : R» << amtGift;
cout << endl << endl;
amtSpentPerChild = calcActualAmount(amtGift, nrChildren);
cout << endl << » Actual amount spent per child : R» ;
cout << amtSpentPerChild << endl << endl;
totalSpent = calcTotalSpent(nrChildren, amtSpentPerChild);
cout << endl << » The actual amount spent was : R» ;
cout << totalSpent << endl;
system(«pause»);
return 0;
}
Last edited on
Use [code][/code] tags next time.
Your problem is that you need a ‘}’ before your while there. Go look at the syntax for a do…while loop again and you should see it.
Home »
C programs »
C common errors programs
Here, we will learn why an error: expected ‘)’ before ‘;’ token occurs and how to fix it in C programming language?
Submitted by IncludeHelp, on September 04, 2018
The error: expected ‘)’ before ‘;’ token may occur by terminating the statements which should not be terminated by the semicolon.
Consider the given example, here I terminated the #define statement by the semicolon, which should not be terminated.
Example:
#include <stdio.h> #define MAX 10; int main(void) { printf("MAX = %dn", MAX); return 0; }
Output
prog.c: In function 'main':
prog.c:3:15: error: expected ')' before ';' token
#define MAX 10;
^
prog.c:6:23: note: in expansion of macro 'MAX'
printf("MAX = %dn", MAX);
^~~
How to fix?
To fix this error, check the statement which should not be terminated and remove semicolons. To fix this error in this program, remove semicolon after the #define statement.
Correct code:
#include <stdio.h> #define MAX 10 int main(void) { printf("MAX = %dn", MAX); return 0; }
Output
MAX = 10
C Common Errors Programs »
-
Здравствуйте.
Помогите, пожалуйста, разобраться.С видео напечатал код в IDE. Выдаёт ошибку expected ‘)’ before ‘;’ token
Причём, две одинаковых строчки, но с разницей только, что одна про минуты, а вторая про секунды, но как их не меняй местами, всегда ругается именно на ту, что с секундами:
int seconds = numberOfSeconds(timeRemaining);
Полный текст ошибки:
C:Arduino2 minsketch_may05asketch_may05a.ino: In function ‘void countdown()’:sketch_may05a:30:49: error: expected ‘)’ before ‘;’ token
int seconds = numberOfSeconds(timeRemaining);
^
exit status 1
expected ‘)’ before ‘;’ tokenВот этот кусок кода в видео:
А вот этот же кусок кода после компиляции у меня:
Если поменять порядок на
int minutes = numberOfMinutes(timeRemaining);
int seconds = numberOfSeconds(timeRemaining);
то он откомпилирует строчку с минутами и будет ругаться на вторую строчку с секундами.
Код целиком:
#define numberOfSeconds(_time_) ((_time_ / 1000%60)
#define numberOfMinutes(_time_) (((_time_ / 1000) / 60) % 60)#include <TM1637Display.h>
const uint8_t OFF[] = {0, 0, 0, 0};
const uint8_t PLAY[] = {B01110011, B00111000, B01011111, B01101110};TM1637Display display(2, 3); // Clock pin, Data pin
unsigned long timeLimit = 3600000;
void setup() {
Serial.begin(9600);
//set brightness
display.setBrightness(0x0c);
//clear the display
display.setSegments(OFF);}
void countdown() {
unsigned long timeRemaining = timeLimit — millis();
while (timeRemaining > 0) {
int seconds = numberOfSeconds(timeRemaining);
int minutes = numberOfMinutes(timeRemaining);display.showNumberDecEx(seconds, 0, true, 2, 2);
display.showNumberDecEx(minutes, 0x80 >> 3, true, 2, 0);timeRemaining = timeLimit — millis();
}
}void loop() {
countdown();}
Последнее редактирование: 5 май 2020
-
В первой строке в коде пропущена скобка. Нужно так:
#define numberOfSeconds(_time_) ((_time_ / 1000%60)) -
Это помогло. Очень благодарен!)) Спасибо.
|
zhundik 0 / 0 / 1 Регистрация: 12.03.2014 Сообщений: 61 |
||||||||||||||||
|
1 |
||||||||||||||||
|
16.10.2014, 20:23. Показов 29048. Ответов 8 Метки нет (Все метки)
Ребят, подскажите(( Изучал Страуструпа, но застрял .. Теперь взял Дейтелов , пока вроде ничего )) Но только вот уже на втором проекте выскочила какая-то беда, и никак не пойму в чем подвох((
Это сам класс
Ну и программка
Вот здесь мне пишет ошибку —
__________________
0 |
|
DrOffset 16495 / 8988 / 2205 Регистрация: 30.01.2014 Сообщений: 15,611 |
||||
|
16.10.2014, 20:31 |
2 |
|||
|
Решение
Вот здесь мне пишет ошибку — Тут надо вместо точек с запятой просто запятые поставить. Добавлено через 3 минуты
1 |
|
0 / 0 / 1 Регистрация: 12.03.2014 Сообщений: 61 |
|
|
16.10.2014, 20:38 [ТС] |
3 |
|
DrOffset, ох я лол Добавлено через 2 минуты Добавлено через 36 секунд
0 |
|
DrOffset 16495 / 8988 / 2205 Регистрация: 30.01.2014 Сообщений: 15,611 |
||||||||
|
16.10.2014, 20:38 |
4 |
|||||||
|
теперь пишет совсем для меня что-то не ясное error: prototype for ‘Invoice::Invoice(std::string, std::string, int, int)’ does not match any in class ‘Invoice’| Ну так присмотрись, действительно такого объявления в классе нет. Вместо него у тебя там объявлен конструктор в двумя параметрами:
Сделай так:
0 |
|
0 / 0 / 1 Регистрация: 12.03.2014 Сообщений: 61 |
|
|
16.10.2014, 20:45 [ТС] |
5 |
|
DrOffset, Вопрос не по теме можно?! Книжка Дейтелов хорошая? Если не читали, то с какой начинали сами?
0 |
|
16495 / 8988 / 2205 Регистрация: 30.01.2014 Сообщений: 15,611 |
|
|
16.10.2014, 20:48 |
6 |
|
Если не читали, то с какой начинали сами? Я Страуструпа читал (Язык программирования С++, по-моему первое еще издание), но тут многие говорят, что она тяжелая (лично я так не думаю).
0 |
|
0 / 0 / 1 Регистрация: 12.03.2014 Сообщений: 61 |
|
|
16.10.2014, 20:52 [ТС] |
7 |
|
DrOffset,а я начинал(Страуструп Б. — Программирование. Принципы и практика использования C++ ), но застрял где он начинает программировать калькулятор. Где идет считывание лексем, термов, выражений и т.д Вот тут то я и запутался, слишком много всего сразу непонятного и без особого пояснения кода
0 |
|
16495 / 8988 / 2205 Регистрация: 30.01.2014 Сообщений: 15,611 |
|
|
16.10.2014, 20:55 |
8 |
|
zhundik, все потому, что эта книжка не учебник. Следовательно читать ее последовательно не нужно. Читать надо там, где идет. Если где-то не идет, то можно переходить к другой главе. Особо ничего не пострадает, т.к. книга написана в расчете на такое прочтение. А потом можно вернуться к непонятному месту. Но Липпман для начинающих все равно лучше. И ее хватит очень надолго, т.к. там и для среднего уровня программиста достаточно материала.
0 |
|
0 / 0 / 1 Регистрация: 12.03.2014 Сообщений: 61 |
|
|
16.10.2014, 21:02 [ТС] |
9 |
|
DrOffset, Ладно спасибо) Сейчас все-таки Дейтелов дочитаю, а потом посмотрю, как-то они меня своим ООП уже в 3-й главе заинтересовали
0 |

![[IMG]](https://psv4.userapi.com/c856216/u17627067/docs/d1/927503d55c79/2020-05-05_02-04-53.png?extra=LVukoElkftYsOyK1krRkFgLWG1NDFDQDEal2z1osUrbk-TwYnR9i1yVmCzq8e0cVJoYrZRgVwz4jXZPm9OReUP4F4EbFSR0pXGcQaVQ4Y1N5ue0vD6aZLYU-t9Q31_ef0ah3Sx1CusVDLKiGkXxIW9U)
![[IMG]](https://psv4.userapi.com/c856236/u17627067/docs/d2/c68b762f0b08/2020-05-05_02-11-13.png?extra=Fab7da21Q8iUxDYwK9mh9PxHXKsurLmubLC4uTgelrkc7SBI6inhTV3kRjNvlfkfIRTr7KGlXUfKvykfsRuQdqqdIcWJFqvbQGTiYfxJK7sQPObjxuwBq7UOsQ9rLr5iu4cbqzplRjm7zu0b4LhV6dg)
Сообщение было отмечено zhundik как решение

Поставил! Только теперь пишет совсем для меня что-то не ясное error: prototype for ‘Invoice::Invoice(std::string, std::string, int, int)’ does not match any in class ‘Invoice’|
А то структурное надоело уже, а программки-то хочется писать побольше))