Floating point exception как исправить

Floating point exception (core dumped) can be a tough and frustrating error to deal with. Read this guide and let our experts teach you how to fix it.

How to fix floating point exception core dumpedFloating point exception (core dumped) is an error that arises when your application tries to do something that is not allowed with a floating point number. In this article, we’ll teach you why the floating point exception occurs and how to fix it. Also, we’ll give you other information about this error. Keep on reading to gain in-depth knowledge on this error and how to prevent it in the future.

Floating point exception occurs because of several reasons such as invalid operation, division by zero, overflow, underflow, or inexact. In this section, we’ll be going through these reasons one by one.

– Invalid Operation

An invalid operation occurs when an operation cannot be represented or has no mathematical value. For example, the square root of a negative number or the logarithm of a negative number falls into this category. We know that in the context of complex numbers you can take the square root of a negative number, but there is no way to represent this in computers.

Also, if your program performs a floating-point operation on a location meant for integer, this will cause an invalid operation. That is because there is a discrepancy between the stored data (integer) and the operation you are trying to perform on the data (floating-point operation).

– Division by Zero

When you try to divide a number by zero, you’ll get a floating-point exception. The same happens when you try to divide by infinity or NaN. The following are examples:

  • -1/0
  • log(0)

– Overflow

An overflow exception occurs when an operation produces a value that is outside of its range. This means that the value is either higher or lower than the smallest representable value.

– Underflow

When the result of a calculation is smaller than what can be stored in a data type, underflow occurs.

– Inexact

An inexact exception occurs when the result of an operation is not equal to the expected value. This happens when you do the operation with exponent range and unbound precision.

How to Fix Floating Point Exception (Core Dumped)

You can fix the floating-point exception by avoiding invalid operations, avoiding computations that lead to division by zero, avoiding overflow, and avoiding underflow. The following steps will go into detail on how to solve floating point exception (core dumped):

– Avoid Invalid Operation

When performing computations in your code, it’s very easy to run into an invalid operation. However, if you are on the lookout, you can avoid such situations. For example, you can implement a check that’ll stop a calculation with a negative number. Another example is an attempt to compute a string and a number.

Also, if you are using OpenFOAM, ensure your mesh is correct and your courant number is not too high. Otherwise, you’ll get a floating point exception (core dumped) OpenFOAM error. In addition, when you are using Gromacs, ensure your simulation is correct. Otherwise, you can get a floating point exception (core dumped) gromacs error.

What’s more, you can run into a floating point exception (core dumped) ubuntu error when you are using Packet Tracer or BRM client in Ubuntu. In both cases, you will need to install the right software to get rid of the error. As a final note, avoid using negatives with conditional checks in your code.

– Avoid Computations That Lead to Division by Zero

You can run into computations that lead to division by zero when you are working on an array using a for loop. One of the best ways to do this is to check if the denominator is zero before you divide. This will avoid the floating-point exception error. Another option is to use try-catch block or try-except block in supported programming languages.

In Python, the try-except block will prevent floating point exception (core dumped) python error. What’s more, there have been reported cases where division by zero leads to floating point exception (core dumped) pytorch error. Meanwhile, in Assembly language, division by zero can lead to floating point exception (core dumped) assembly error.

The same happens when using the Netwide Assembler (NASM), where you’ll get floating point exception (core dumped) nasm error when you divide a number by zero.

– Avoid Overflow

You can avoid overflow by making sure you do not go above what a particular data type can store. Code examples will help you better understand what we are talking about, so let’s see some code examples.

In the C code detailed below, we have an unsigned char that can take a maximum of 256 characters. However, we set its initial value to 250 and then we perform a loop that requests for the next 10. This means we are asking for 260 characters from 256, hence an overflow occurs. We show the overflow by printing the hexadecimal equivalent of the numbers.

#include <stdio.h>
int main(int argc, char* argv[]) {
// Declare an unsigned char
unsigned char n = 250;
int i;
// Print the numbers in Hexadecimal
// and ordinary number
for (i = 0; i < 10; i++) {
printf(“%hhu | %hhXn”, n, n);
n++;
}
return 0;
}

The following is the output of the code above:

250 | FA
251 | FB
252 | FC
253 | FD
254 | FE
255 | FF
0 | 0
1 | 1
2 | 2
3 | 3

– Avoid Underflow

You can prevent underflow by not taking away from a data type more than what it can provide. If you don’t, an underflow will happen.

In the code example below, we have an unsigned char whose value is five. Afterwards, we loop over it 10 times, decrementing the loop counter at every iteration. In the end, only the first five counters will output the correct result. The rest will produce an underflow.

#include <stdio.h>
int main(int argc, char* argv[]) {
// Declare an unsigned char
unsigned char n = 5;
int i;
// Print the numbers with for-loop
for (i = 0; i < 10; i++) {
printf(“%hhu | %hhXn”, n, n);
n–;
}
return 0;
}

The output of the code:

5 | 5
4 | 4
3 | 3
2 | 2
1 | 1
0 | 0
255 | FF
254 | FE
253 | FD
252 | FC

Useful Information About the Floating-point Exception Error

In this section, we’ll discuss related information about the floating-point exception. This will be more like a question-and-answer conversation. We’ve outlined the most commonly-asked questions below, with expert answers following.

– What Is Floating-point Exception Sigfpe?

Floating-point exception SIGFPE is a signal raised by floating-point exception which results in the process termination and production of a core file. Meanwhile, the former and the latter will occur in the absence of a signal-handler subroutine. However, if there is a signal handler subroutine, the process calls it instead.

– What Is Floating-point Numbers Represented As?

Floating-point numbers are represented as scientific notation, so the scientific notation can be written as F multiplied by two raised to an Exponent, where F is the Fraction, E is the Exponent and the number two is the Radix. Meanwhile, both the Fraction and Exponent can be positive or negative numbers.

Also, modern computers use the IEEE 754 standard to represent floating-point numbers. For example, 2.6, 0.28, and negative 11.34 are all floating-point numbers. However, numbers like 80 and 70 are not floating-point numbers.

– How Can We Avoid Floating-point Exception in Fluent?

You can avoid floating-point exceptions in Fluent by setting your mesh to CFD. Here is a more detailed step-by-step process to do this:

  1. Set your mesh to CFD.
  2. The mesh should have an orthogonal array value with good skewness.
  3. Your mesh should be unstructured and arranged in triangles arrangement.
  4. Show all the bodies of your geometry in your mesh without cuts.
  5. If there is improper initialization, reset and start again.
  6. If you are doing transient apps, select Pressure-Implicit with Splitting of Operator (PISO).
  7. Set your timestamps to less than 5 multiply by 10 exponential negative 3.
  8. Activate Implicit Update Settings.

– How Do You Stop a Floating Error in Python?

You cannot stop floating errors, however, you can manage them by using another representation for the values for precise computation. For example, if you need exact decimal rounding, you can represent the values as binary-coded decimals.

– How Are Floating-point Numbers Stored?

Floating-point numbers are stored as the significand and the exponent with a sign bit. The high-order bit indicates a sign. Meanwhile, zero indicates a positive value, while one indicates a negative value. As a result, the exponent is the remaining eight bits.

Conclusion

This article explained floating-point exception and how to fix floating-point exception (core dumped); we also learned about other information that related to this error. The following points were tackled in this guide:

  • Floating-point exception when there is an error in floating-point arithmetic.
  • Causes of floating-point exception include invalid operation and overflow.
  • You cannot avoid floating-point errors, but you can manage them.
  • SIGFPE is a signal raised by the floating-point exception.
  • Floating-point exception can occur in applications like OpenFoam, Gromacs, and Fluent by Ansys.

Floating point exception core dumped errorWith everything that we’ve taught you in this article, you are now well-prepared to tackle floating-point exception confidently.

  • 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

I am not sure how to deal with floating point exceptions in either C or C++. From wiki, there are following types of floating point exceptions:

IEEE 754 specifies five arithmetic errors that are to be recorded in "sticky bits" (by default; note that trapping and other alternatives are optional and, if provided, non-default).  

* inexact, set if the rounded (and returned) value is different from the mathematically exact result of the operation.  
* underflow, set if the rounded value is tiny (as specified in IEEE 754) and inexact (or maybe limited to if it has denormalisation loss, as per the 1984 version of IEEE 754), returning a subnormal value (including the zeroes).  
* overflow, set if the absolute value of the rounded value is too large to be represented (an infinity or maximal finite value is returned, depending on which rounding is used).  
* divide-by-zero, set if the result is infinite given finite operands (returning an infinity, either +∞ or −∞).  
* invalid, set if a real-valued result cannot be returned (like for sqrt(−1), or 0/0), returning a quiet NaN.

Is it that when any type of above exceptions happens, the program will exit abnormally? Or the program will carry this error on without mentioning anything and therefore make the error hard to debug?

Is a compiler like gcc able to give warning for some obvious case?

What can I do during coding my program to notify where the error happens and what types it is when it happens, so that I can locate the error easily in my code? Please give solutions in both C and C++ case.

Thanks and regards!

Community's user avatar

asked Feb 8, 2010 at 2:24

Tim's user avatar

3

There are many options, but the general and also the default philosophy introduced by 754 is to not trap but to instead produce special results such as infinities that may or may not show up in important results.

As a result, the functions that test the state of individual operations are not used as often as the functions that test the representations of results.

See, for example…

LIST OF FUNCTIONS

 Each of the functions that use floating-point values are provided in sin-
 gle, double, and extended precision; the double precision prototypes are
 listed here.  The man pages for the individual functions provide more
 details on their use, special cases, and prototypes for their single and
 extended precision versions.

 int fpclassify(double)
 int isfinite(double)
 int isinf(double)
 int isnan(double)
 int isnormal(double)
 int signbit(double)

Update:
For anyone who really thinks FPU ops generate SIGFPE in a default case these days, I would encourage you to try this program. You can easily generate underflow, overflow, and divide-by-zero. What you will not generate (unless you run it on the last surviving VAX or a non-754 RISC) is SIGFPE:

#include <stdio.h>
#include <stdlib.h>
int main(int ac, char **av) { return printf("%fn", atof(av[1]) / atof(av[2])); }

answered Feb 8, 2010 at 2:42

DigitalRoss's user avatar

DigitalRossDigitalRoss

142k24 gold badges243 silver badges328 bronze badges

3

On Linux you can use the GNU extension feenableexcept (hidden right at the bottom of that page) to turn on trapping on floating point exceptions — if you do this then you’ll receive the signal SIGFPE when an exception occurs which you can then catch in your debugger. Watch out though as sometimes the signal gets thrown on the floating point instruction after the one that’s actually causing the problem, giving misleading line information in the debugger!

answered Feb 8, 2010 at 3:10

Mike Dinsdale's user avatar

1

On Windows with Visual C++, you can control which floating-point exceptions are unmasked using _control87() etc.. Unmasked floating-point exceptions generate structured exceptions, which can be handled using __try/__except (and a couple of other mechanisms). This is all completely platform-dependent.

If you leave floating point exceptions masked, another platform-dependent approach to detecting these conditions is to clear the floating-point status using _clear87() etc., perform computations, and then query the floating-point status using _status87() etc..

Is any of this any better than DigitalRoss’s suggestion of checking the result? In most cases, it’s not. If you need to detect (or control) rounding (which is unlikely), then maybe?

On Windows with Borland/CodeGear/Embarcadero C++, some floating-point exceptions are unmasked by default, which often causes problems when using third-party libraries that were not tested with floating-point exceptions unmasked.

answered Feb 8, 2010 at 6:52

bk1e's user avatar

bk1ebk1e

23.7k6 gold badges54 silver badges65 bronze badges

Different compilers handle these errors in different ways.

Inexactness is almost always the result of division of numbers with an absolute value greater than one (perhaps through trancendental functions). Adding, subtracting and multiplying numbers with an absolute value > 1.0 can only result in overflow.

Underflow doesn’t occur very often, and probably won’t be a concern in normal calculations except for iterated functions such as Taylor series.

Overflow is a problem that can usually be detected by some sort of «infinity» comparison, different compilers vary.

Divide by zero is quite noticable since your program will (should) crash if you don’t have an error handler. Checking dividends and divisors will help avoid the problem.

Invalid answers usually are caught without special error handlers with some sort of DOMAIN error printed.

[EDIT]

This might help: (Numerical Computation Guide by Sun)
http://docs.sun.com/source/806-3568/

answered Feb 8, 2010 at 2:43

Arthur Kalliokoski's user avatar

C99 introduced functions for handling floating point exceptions. Prior to a floating point operation, you can use feclearexcept() to clear any outstanding exceptions. After the operation(s), you can then use fetestexcept() to test which exception flags are set.

answered Feb 8, 2010 at 3:15

caf's user avatar

cafcaf

230k38 gold badges318 silver badges459 bronze badges

In Linux, you can trap these exceptions by trapping the SIGFPE signal. If you do nothing, these exceptions will terminate your program. To set a handler, use the signal function, passing the signal you wish to have trapped, and the function to be called in the event the signal fires.

answered Feb 8, 2010 at 2:43

sizzzzlerz's user avatar

sizzzzlerzsizzzzlerz

4,2153 gold badges26 silver badges35 bronze badges

2

Kuwadorian

0 / 0 / 0

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

Сообщений: 3

1

26.09.2022, 00:50. Показов 1612. Ответов 4

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


Здравствуйте, изучаю си четвертый день и впервые столкнулся с ошибкой Floating point exception подскажите пожалуйста, что провоцирует вызов ошибки в этой программе.
Условие задачи:

Кликните здесь для просмотра всего текста

Допустим, у вас имеется N хоккеистов. Из них нужно сформировать команду из K человек. Сколько существует вариантов это сделать? На подобные вопросы существует стандартный ответ — число сочетаний, которое вычисляется по следующей формуле:

Ошибка Floating point exception

Ошибка:Failed test #4 of 13. Runtime error

Error:
Floating point exception

Код:

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
#include<stdio.h>
int factorial(int p){
  int p1 = p;
 for (int i=1; i<=p1-1;++i) {
  p=p*i;   
 }
 return p;
}
int combin(int n, int k){
 int c,c1;
    c1=(n-k);
    c=factorial(n)/(factorial(k)*factorial(c1));
    return c;
}
 
int main(void){
    int n = 0, k = 0;
    scanf("%d%d",&n,&k);
    if (n != 0 && k != 0) {
    printf("%d",combin(n,k)); }
    else printf("%d",1);
 
    return 0;
}

Заранее спасибо!

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



0



412 / 359 / 89

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

Сообщений: 1,038

26.09.2022, 02:01

2

Лучший ответ Сообщение было отмечено Kuwadorian как решение

Решение

Вы какие числа туда вводите? Судя по ошибке, они великоваты — получившиеся факториалы в int не лезут.



1



0 / 0 / 0

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

Сообщений: 3

26.09.2022, 02:06

 [ТС]

3

Спасибо, числа строго меньше 12, а я как-то и не подумал про то что факториал 11 будет настолько большим. А я уже весь код переписал, наступив на те же грабли



0



412 / 359 / 89

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

Сообщений: 1,038

26.09.2022, 02:17

4

Если в условии это (что числа не больше 12) задано, то можно сравнительно легко решить проблему: выбрав большее из чисел k и n-k, сразу «убрать» из n! соответствующие множители — до 16 дотянете. Но можно и не думать и просто сменить int на unsigned long long.



0



357 / 260 / 105

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

Сообщений: 1,604

26.09.2022, 02:32

5

A! / B!, B <= A

int ( 4 bytes ) —> [ -2^31; +2^31 — 1] ~ [ -2 млрд; +2млрд ]

12! = 479 001 600 — ок
13! = 6 227 020 800 — bad

A = 15, B = 7
A! / B! = 15! / 7! = ( 1 * 2 * .. * 15 ) / ( 1 * 2 * .. * 7 ) = 8 * 9 * … * 15 = 259 459 200

15! / 7! <——> 8 * 9 * … * 15 — not problem for int….
————————
A = 101, B = 99
A! / B! = 101! / 99! = 100 * 101 = 10 100 — ok



0





vin_erra

Автор:

vin_erra,
25 сентября 2011 в ANSYS CFX

  • Ответить в тему

  • Создать тему

Рекомендованные сообщения


vin_erra

vin_erra

0


    • Жалоба
    • Рассказать

Здравствуйте уважаемые форумчане)

я произвожу расчет в Cfx входного аппарата компрессора. и в Solver он мне выдает ошибку «Floating point exception: Overflow «. сначала он мне выдал это после 6 итерации. тогда я сменила модель турбулентности с к-эпсилон на SST, он посчитал тогда уже 28 итераций и снова выдал мне эту же ошибку.

чем это может быть вызвано и что в этом случае можно предпринять??

  • Цитата
Ссылка на сообщение
Поделиться на других сайтах


stydentium

stydentium

0


    • Жалоба
    • Рассказать

Проверьте масштабы импортируемой в CFX модели… или какая-то из входных/выходных переменных из ГУ задана не в тех единицах…

  • Цитата
Ссылка на сообщение
Поделиться на других сайтах
  • 1 месяц спустя…


Red Ember

Red Ember

0


    • Жалоба
    • Рассказать

не так давно столкнулся с этим при задании теплового потока. потом глянул (я его через expressions задавал) — ба! ошибся на порядок в формуле для теплоемкости, после чего тепловой поток расходится просто астрономически)))

Проверьте физические величины (например, если задавали материалы и их свойства), поставьте точки для отслеживания величин различных параметров

  • Цитата
Ссылка на сообщение
Поделиться на других сайтах


sergeyd

sergeyd

3


    • Жалоба
    • Рассказать

для начала нужно посмотреть сетку. Вероятно, она излишне груба.

sst менее требовательна к ее качеству. и вытерпела дольше.

  • Цитата
Ссылка на сообщение
Поделиться на других сайтах


Doomed

Doomed

0


    • Жалоба
    • Рассказать

Ошибка «Floating point exception: Overflow» обычно означает, что какая то расчетная величина превысила допустимые пределы.

Это бывает если есть плохой элемент в сетке и в этом месте большая погрешность численной схемы, иногда — если задаете стенку с проскальзыванием, если входные/выходные условия заданы неверно(например иногда при задании входных и выходных условий давлением задача расходится или при задании очень больших скоростей), если вводите дополнительные переменные определяя, например, свойства расчетной среды через expressions и там есть ошибка. Может быть в каком то месте расчета возникло деление на ноль.

  • Цитата
Ссылка на сообщение
Поделиться на других сайтах
  • 2 недели спустя…


vitefimov

vitefimov

0


    • Жалоба
    • Рассказать

попробуйте уменьшить Phisical Timescale в Solver Control

  • Цитата
Ссылка на сообщение
Поделиться на других сайтах

Присоединяйтесь к обсуждению

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

Если у вас есть аккаунт, войдите в него для написания от своего имени.

Примечание: вашему сообщению потребуется утверждение модератора, прежде чем оно станет доступным.

  • Сейчас на странице

      0 пользователей

    Нет пользователей, просматривающих эту страницу.

  • Сообщения


    • maxx2000

      Автор:

      maxx2000 · Опубликовано: 3 минуты назад

      EX_CIRCLE             : N G17 CIRCLEDIRECTION X* Y* Z I* J* F
      EX_CIRCLEZX         : N G18 CIRCLEDIRECTION X* Y Z* I* K* F

      EX_CIRCLEYZ         : N G19 CIRCLEDIRECTION X Y* Z* J* K* F

      А ось ориентации совсем тут не причём на обычном трёх осевом можно резать дуги и по G18 и по G19

      obrezka.nc

      Или о чём речь?


    • Maze

      Автор:

      Maze · Опубликовано: 4 минуты назад

      Трудности в виде скудности курсов по ПО. Курсы от дилера либо крайне скупы, либо так перегружены информацией, что её прорабатывать надо несколько дней.. особенно модуль Архив в ЛОЦМАН.ПЛМ и бизнес-процессы.. Тут нужна команда работающая исключительно на ПЛМ.

      Ну и учитывайте то, что быстрой отдачи от ПЛМ не получите.


    • Fedor


    • gudstartup

      Автор:

      gudstartup · Опубликовано: 17 минут назад

      Тут не действует принцип помогите чем можете совет должен быть конкретным на основе изложенных автором фактов и более подробной инфе об оборудовании. Ошибку перевели срабатывание датчиков легко посмотреть и ориентируясь по схеме найти их на входах PMC а далее выяснить что же заставляет выдавать логику выдавать сигнал об ошибке! 

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

       

       


    • Jesse

      Автор:

      Jesse · Опубликовано: 18 минут назад

      испытание дома и испытания яиц подрядчика

       

      а меня больше смутило, что он слишком быстро выходит на определённую частоту. Землетрясение всё-таки действует в относительно широком диапазоне частот 0-33 Гц. Имхо надо было очень плавно разгонять шайтан-машину и с выходом на условные 35-40 Гц…

       

      ну хз.. вот родители живут в Дагестане. Там недалеко от Махачкалы есть небольшой разломчик — Буйнакский разлом. В 1970 тряхануло так тряхануло! Магнитуда 6,7.
       

      Представьте какой это «обосрыш» — когда на тебя идут земельные волны https://ru.wikipedia.org/wiki/Дагестанское_землетрясение_1970_года#:~:text=Дагестанское землетрясение 1970 года — катастрофическое,-северо-западу от Махачкалы.


    • KAMALOV

      Автор:

      KAMALOV · Опубликовано: 36 минут назад

      Алексей ну выше же написал, скинь PLC ответ сразу получишь

      стойки все разные, я имею введу, программирует их разные люди, у нас на производстве станки одной и той же модели от одной и той же фирмы не то что PLC по разному пишут, даже принципиальные схемы не совпадают, а вы нам предлагаете гадать, Limon2010 вам уже примерно обьяснил что не так может быть со станком


    • PROXXGT

      Автор:

      PROXXGT · Опубликовано: 36 минут назад

      Доброго времени суток. Появилась нужда добавить в постпроцессор подпрограмму, для автоматического выбора плоскости замены  дуг (G17,G18,G19) — для токарно-фрезерного в зависимости от ориентации оси инструмента. Вопрос, какой параметр отвечает за ось ориентации ? Можно через обычное сравнения с таким параметром написать подпрограмму и вывести в пост код с включением нужной плоскости ?


    • alex0800


    • gudstartup


    • статист

      Автор:

      статист · Опубликовано: 42 минуты назад

      Да. И/Или делают расчеты.

      Еще проверяют соблюдение технорм.

      Вот об этом я и говорю, что в Турции видно так было.

  • Forum
  • Beginners
  • Floating Point Exception?

Floating Point Exception?

So I’m still pretty new to C++ and I’m trying to make a text based RPG. I just started and have been trying to work out the fighting system to be object oriented.

I get a runtime error from it that says «Floating point exception (core dumped) Process returned 136 (0x88)» as soon as you try to attack. any ideas why?

I realize this is very long and probably not programmed very well, but I’m still just starting out. Any help would be greatly appreciated!

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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

void battlewin();
void newgame();

bool bw = false;

void RANDSEED()
{
    srand (time(NULL));
}

class userloc{
    private:
        int x, y, maxx, maxy;
    public:
        void set_map(int a, int b)
        {
            maxx = a;
            maxy = b;
            cout << "Map size is: " << maxx << "x" << maxy << ".n";
        }
} map;

class mob{};


class player: public mob{
    public:
        int gold, hp, maxhp, attack;
        string name;
        void newchar()
        {
            hp = 100;
            maxhp = 100;
            attack = 10;
            gold = 0;
        }
        void deathchk()
        {
            if(hp<=0)
            {
                cout << "You have died!n";
                cout << "Press any button to exit.";
                cin.ignore();
                exit(0);
            }
        }
        void takedmg(int atk)
        {
            int dmg;
            dmg = rand() % atk + 1;
            hp-=dmg;
            cout << "The mob has hit you for " << dmg << endl;
            cout << "You have " << hp << "/" << maxhp << " HP." << endl;
            deathchk();
        }
} user;

class enemy: public mob{
    public:
        int goldvalue, hp, attack;
        void deathchk()
        {
            if(hp<=0)
            {
                battlewin();
            }
        }
        void takedmg(int atk)
        {
            int dmg;
            dmg = rand() % atk + 1;
            hp-=dmg;
            cout << "You hit the mob for " << dmg << endl;
            cout << "Mob has " << hp << " HP." << endl;
            deathchk();
        }
        void spawn(int o, int t, int th)
        {
            hp = rand() % o + 1;
            attack = rand() % t + 1;
            goldvalue = rand() % th + 1;
        }
};

void newgame()
{
    user.newchar();
}

void battlewin()
{
    cout << "Congratulations! You won the battle.";
    cout << "You have " << user.hp << "/" << user.maxhp << " HP.n";
    bw = true;
}


void fight()
{
    enemy i;
    i.spawn(50, 10, 10);
    while(bw==false)
    {
        int choice;
        cout << "Press 1 to attack. ";
        cin >> choice;
        if(choice==1)
        {
            i.takedmg(user.attack);
            if(bw==false)
            {
                user.takedmg(i.attack);
            }
        }
    }
    bw=false; // if you're here you won
    user.gold+=i.goldvalue;
    cout << "Mob dropped " << i.goldvalue << " gold!" << endl;
}

int main()
{
    RANDSEED();
    player user;
    user.newchar();
    cout << "Please enter your name: ";
    getline(cin,user.name);
    cout << "Welcome, " << user.name << " to RPG fight!n";
    fight();
    cout << bw;
    return 0;
}

Last edited on

This happens because you have the user defined twice in your code. Once in line 62 in the global scope and once in line 130 in the scope of function main. When you call newchar() in line 131 it operates on the second «user» variable, while one in global scope remains uninitialized. After that everywhere you use the «user» from the global scope, which leads to the exception here: dmg = rand() % atk + 1; because the atk variable happened to be initialized with 0 (which you should never rely on). So to solve your current problem, remove line 130, so that the global user gets initialized in line 131.

As you said, this code is far from being perfect, so I just concentrated on the question you had. To find this kind of bugs — use a debugger to see what your program does step-by-step (I assume you work in an IDE, and pretty much all of them have this functionality).

Good luck with learning C++ :)

dmg = rand() % atk + 1; and similar.

atk is zero. The modulo operator is meaningless applied mod zero

e.g. 7 % 0 causes a problem

Try dmg = rand() % (atk + 1); and similar.

Last edited on

Thanks for the replies. They were both helpful and I will try these solutions out later today when I have time. I’ll let you know how they work out.

Thanks guys! I followed both of your advice and the exception error went away.

Topic archived. No new replies allowed.

Уважаемые форумчане, Вот столкнулся с такой проблемой: расчитываю перехлдной процесс воды в лед по времени. Задал плотность и вязкость воды в зависимотси от тмпературы. В процессе расчета все идет нормально, но как только вода становится 0 градусов расчет вылетает вот с такой ошибкой:

turbulent viscosity limited to viscosity ratio of 1.000000e+06 in 302 cells 
  7233  1.2247e-01  1.6512e-06  5.6676e+01  7.7533e-05  9.2412e-12  3.1982e+06  7.3065e+14  0:00:07    7

 turbulent viscosity limited to viscosity ratio of 1.000000e+06 in 140 cells 
  7234  2.5156e+02  1.6248e-01  1.0288e+00  1.4041e-02  4.8439e-07  7.1952e-01  7.8450e-01  0:00:05    6

 turbulent viscosity limited to viscosity ratio of 1.000000e+06 in 129 cells 
  7235  1.0365e+03  1.6727e-01  5.3040e-02  7.0450e-02  2.2107e-07  6.2509e-01  7.4555e-01  0:00:04    5
# Divergence detected in AMG solver: temperature -> Increasing relaxation sweeps!
# You may try the enhanced divergence recovery with (rpsetvar ‘amg/protective-enhanced? #t)

Divergence detected in AMG solver: temperature
Divergence detected in AMG solver: temperature
Divergence detected in AMG solver: temperature
Divergence detected in AMG solver: temperature temperature limited to 1.000000e+00 in 476 cells on zone 2 in domain 1

 
 turbulent viscosity limited to viscosity ratio of 1.000000e+06 in 258 cells 

Error at Node 0: floating point exception

Error at Node 1: floating point exception

Error at Node 2: floating point exception

Error at Node 3: floating point exception

Error at host: floating point exception

Error: floating point exception
Error Object: #f

Подскажите пожалуйста как это решить?

вот параметры сетки 

 Domain Extents:
   x-coordinate: min (m) = 0.000000e+00, max (m) = 1.500000e-02
   y-coordinate: min (m) = 7.750000e-02, max (m) = 9.250000e-02
 Volume statistics:
   minimum volume (m3): 3.937486e-10
   maximum volume (m3): 1.878569e-09
     total volume (m3): 1.201659e-04
   minimum 2d volume (m3): 7.573330e-10
   maximum 2d volume (m3): 3.526105e-09
 Face area statistics:
   minimum face area (m2): 1.649600e-05
   maximum face area (m2): 7.817368e-05
 Checking mesh……………………………….
Done.

Mesh Quality:

Minimum Orthogonal Quality =  5.95791e-01
(Orthogonal Quality ranges from 0 to 1, where values close to 0 correspond to low quality.)

Maximum Ortho Skew =  3.55123e-01
(Ortho Skew ranges from 0 to 1, where values close to 1 correspond to low quality.)

Maximum Aspect Ratio =  4.18113e+00

Понравилась статья? Поделить с друзьями:
  • Floating point error overflow encountered in exp
  • Floating point division by zero как исправить delphi
  • Float object is not subscriptable как исправить
  • Float object is not iterable python ошибка
  • Float object is not callable ошибка