Divide by zero как исправить

C# novice here, when the int ‘max’ below is 0 I get a divide by zero error, I can see why this happens but how should I handle this when max is 0? position is also an int.

    private void SetProgressBar(string text, int position, int max)
    {
        try
        {
            int percent = (100 * position) / max; //when max is 0 bug hits
            string txt = text + String.Format(". {0}%", percent);
            SetStatus(txt);
        }
        catch
        {
        }
    }

Aziz Shaikh's user avatar

Aziz Shaikh

16.2k11 gold badges62 silver badges79 bronze badges

asked Oct 1, 2008 at 22:55

1

int percent = 0
if (max != 0) percent = (100*position) / max

rjzii's user avatar

rjzii

14.1k12 gold badges78 silver badges119 bronze badges

answered Oct 1, 2008 at 22:57

Simon's user avatar

SimonSimon

78.2k25 gold badges88 silver badges118 bronze badges

0

Well, that entirely depends on the behaviour you want. If the maximum value of your program bar is zero, is it full? Is it empty? This is a design choice, and when you’ve chosen, just test for max == 0 and deploy your answer.

answered Oct 1, 2008 at 22:57

Adam Wright's user avatar

Adam WrightAdam Wright

48.9k12 gold badges130 silver badges152 bronze badges

  • You can throw an exception.
  • You can do int percent = ( max > 0 ) ? (100 * position) / max : 0;
  • You can choose to do nothing instead of assigning a value to percent.
  • many, many other things…

Depends on what you want.

answered Oct 1, 2008 at 22:57

Swati's user avatar

SwatiSwati

49.7k4 gold badges36 silver badges53 bronze badges

Check for zero.

if ( max == 0 ) {
    txt = "0%";
} else {
    // Do the other stuff....

answered Oct 1, 2008 at 22:57

palehorse's user avatar

palehorsepalehorse

26k3 gold badges39 silver badges48 bronze badges

This is not a C# problem, it’s a math problem. Division by zero is undefined. Have an if statement that checks whether max > 0 and only execute your division then.

answered Oct 1, 2008 at 22:58

Esteban Araya's user avatar

Esteban ArayaEsteban Araya

29.2k24 gold badges106 silver badges141 bronze badges

Convert your

int percent = (100 * position) / max;

into

int percent;
if (max != 0)
    percent = (100 * position) / max;
else
    percent = 100; // or whatever fits your needs

answered Oct 1, 2008 at 23:00

tzot's user avatar

tzottzot

91.9k29 gold badges140 silver badges203 bronze badges

Well, if max is zero, then there is no progress to be made. Try catching the exception where this is called. That is probably the place to decide whether there is a problem or if the progress bar should be set at zero or at 100%.

answered Oct 1, 2008 at 22:59

Marcin's user avatar

MarcinMarcin

48.2k18 gold badges127 silver badges200 bronze badges

2

I guess the root question is: Does it make sense to even call this function where max is ‘0’? If yes, then I’d add special handling to it i.e.:

if (max == 0) 
{
    //do special handling here
}
else
{
    //do normal code here
}

If 0 doesn’t make sense, I’d investigate where it’s coming from.

answered Oct 1, 2008 at 22:59

Bob King's user avatar

Bob KingBob King

25.2k6 gold badges54 silver badges66 bronze badges

You would need a guard clause which checks for max == 0.

private void SetProgressBar(string text, int position, int max)
{
    if(max == 0)
        return;
    int percent = (100 * position) / max; //when max is 0 bug hits
    string txt = text + String.Format(". {0}%", percent);
    SetStatus(txt);
}

You could also handle the Divide by Zero exception, as your sample showed, but it is generally more costly to handle exceptions then to set up checks for known bad values.

answered Oct 1, 2008 at 22:59

ckramer's user avatar

ckramerckramer

9,4191 gold badge24 silver badges38 bronze badges

If you are using this for a download, you’ll probably want to show 0% as I assume max would == 0 in this case when you don’t KNOW the file size yet.

int percent = 0;
if (max != 0)
    ...;

If you are using this for some other long task, I’d want to assume 100%

But also, since position can never be between 0 and -1, so you’ll probably want to drop the 100 *

answered Oct 1, 2008 at 23:00

Dre's user avatar

DreDre

4,26830 silver badges39 bronze badges

You can user a ternary operator.

int percent = max != 0 ? (100 * position) / max : 0;

This means that when max does not equal zero, to perform the calculation. If it equals 0 then it will set the percent to 0.

answered Mar 10, 2021 at 1:37

Stephen85's user avatar

Stephen85Stephen85

2501 silver badge15 bronze badges

Ошибка — Warning: Division by zero in, как исправить

Ошибка Division by zero, как исправить ошибку Warning: Division by zero in

division by zero это не ошибка при установке игры — это обычное деление на ноль…

  1. Что означает ошибка Division by zero
  2. Как исправить ошибку Warning: Division by zero in
  1. Что означает ошибка Division by zero

    У нас встретилась вот такая ошибка :

    Warning: Division by zero in адрес on line 18

    Что означает ошибка Division by zero

    Прежде чем приступать к нашей ошибке — давайте просто попробуем перевести!

    Warning: Division by zero — перевод

    Переведем данную ошибку с английского и нам сразу станет все ясно!

    Warning — предупреждение, сигнал сущ

    Division — деление, отдел, раздел, распределение сущ

    by — по, посредством предл

    zero — ноль сущ

    Итого, если мы соберем данную фразу «Warning: Division by zero» на русском, то получим :
    Внимание! Ошибка деления на ноль!

  2. как исправить ошибку Warning: Division by zero in

    Дл ятого, чтобы исправить ошибку «Warning: Division by zero in» нам понадобится скриншот ошибки, который мы приводили раньше. смотрим на него и видим последнее слово и число, line — это линия в файле, 18 — это номер линии где ошибка.

    line 18

    И та часть, которая размыта — это адрес, по которому находится файл с ошибкой Warning: Division by zero in
    как исправить ошибку Warning: Division by zero in

    Далее находим данный файл и удаляем ошибку!

Не благодарите, но ссылкой можете поделиться!

COMMENTS+

 
BBcode


haseki

4 / 4 / 1

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

Сообщений: 164

1

18.10.2015, 15:55. Показов 3234. Ответов 3

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


Студворк — интернет-сервис помощи студентам

Код программы:

Assembler
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
Data SEGMENT                         ;Открыть сегмент данных
    A DW 16h                        ;Инициализировать 
    B DW -50                        ;переменные A, B, C, D, X
    C DW 1Bh
    D DB 3
    X DW ?
Data ENDS                             ;Закрыть сегмент данных
Ourstack SEGMENT Stack                ;Открыть сегмент стека
    DB 100h DUP (?)                  ;Отвести под стек 256 байт
Ourstack ENDS                         ;Закрыть сегмент стека
ASSUME CS:Code, DS:Data, SS:Ourstack  ;Назначить сегментные регистры
Code SEGMENT                          ;Открыть сегмент кодов
    Start: mov AX, Data              ;Инициализировать сегментный
           mov DS, AX                ;регистр DS
           xor AX, AX                ;Очистить регистр AX
           
           mov AL, D                 ;AL = 3
           mul C                     ;AX = C*D
           mov BX, AX                ;BX = C*D
           mov AL, 2                 ;AL = 2
           mul A                     ;AX = 2*A
            mov CX, AX                ;CX = 2*A
           mov DX, CX                ;DX = 2*A
           add DX, B                 ;DX = 2*A + B
           mov AX, BX                ;AX = C*D
           idiv DX                   ;Делим на (2А+В) (частное сохран. в AL)
           mov X, AX                 ;Сохранить результат в Х
 
           mov AX, 4C00h            ;Завершить программу
           int 21h                  ;с помощью DOS
Code ENDS                            ;закрыть сегмент кодов
    END Start                        ;Конец исходного модуля

При трассировке на команде idiv DX выдает ошибку деления на ноль.
Что не так в программе?



0



Charles Kludge

Клюг

7673 / 3188 / 382

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

Сообщений: 8,380

18.10.2015, 16:35

2

Цитата
Сообщение от haseki
Посмотреть сообщение

Что не так в программе?

DX используется командой idiv для хранения остатка, поэтому при делении на DX результат непредсказуем.
Идентификатор «C» является зарезервированным словом для многих трансляторов, поэтому переименовал в «C_».

Assembler
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
;tasm/masm
.model  small
.data                          ;Открыть сегмент данных
    A DW 16h                        ;Инициализировать 
    B DW -50                        ;переменные A, B, C, D, X
    C_ DW 1Bh
    D DB 3
    X DW ?
.stack 
.code                             ;Открыть сегмент кодов
    Start: mov AX, @data              ;Инициализировать сегментный
           mov DS, AX                ;регистр DS
           xor AX, AX                ;Очистить регистр AX
           
           mov AL, D                 ;AL = 3
           mul C_                     ;AX = C*D
           mov BX, AX                ;BX = C*D
           mov AL, 2                 ;AL = 2
           mul A                     ;AX = 2*A
            mov CX, AX                ;CX = 2*A
           mov si, CX                ;si = 2*A
           add si, B                 ;si= 2*A + B
           mov AX, BX                ;AX = C*D
           idiv si                   ;Делим на (2А+В) (частное сохран. в AL)
           mov X, AX                 ;Сохранить результат в Х
 
           mov AX, 4C00h            ;Завершить программу
           int 21h                  ;с помощью DOS
    END Start                        ;Конец исходного модуля



1



4 / 4 / 1

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

Сообщений: 164

18.10.2015, 16:47

 [ТС]

3

Charles Kludge, огромное спасибо, все понятно!



0



Ушел с форума

Автор FAQ

15881 / 7457 / 1010

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

Сообщений: 13,441

20.10.2015, 03:47

4

Цитата
Сообщение от haseki
Посмотреть сообщение

idiv DX выдает ошибку деления на ноль

haseki,
ошибку деления на ноль вызовут также команды idiv ah/dx/edx/rdx и команды div ah/dx/edx/rdx
https://www.cyberforum.ru/asse… 05284.html https://www.cyberforum.ru/cgi-bin/latex.cgi?to «Глава 10. АРИФМЕТИЧЕСКИЕ КОМАНДЫ» https://www.cyberforum.ru/cgi-bin/latex.cgi?to«Команда DIV»/»Команда IDIV»



1



Activity

public class Couple extends AppCompatActivity implements View.OnClickListener {
        private AdView adView;
    
        TextView count_txt, quotes_txt;
        CardView back_btn, copy_btn, share_btn, next_btn;
    
        List<String> quotes_list;
        DatabaseReference databaseReference;
        Model myShayari;
        int position =0;
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.custom_layout);
    
            Toolbar toolbar = findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            getSupportActionBar().setTitle("Couple");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    
            adView= (AdView) findViewById(R.id.adView);
            AdRequest adRequest = new AdRequest.Builder().build();
            adView.loadAd(adRequest);
    
            count_txt = findViewById(R.id.countTEXT);
            quotes_txt = findViewById(R.id.quotesTEXT);
            back_btn = findViewById(R.id.backBtn);
            copy_btn = findViewById(R.id.copyBtn);
            share_btn = findViewById(R.id.shareBtn);
            next_btn = findViewById(R.id.nextBtn);
    
            back_btn.setOnClickListener(this);
            copy_btn.setOnClickListener(this);
            share_btn.setOnClickListener(this);
            next_btn.setOnClickListener(this);
    
    
            databaseReference = FirebaseDatabase.getInstance().getReference("couple");
            myShayari = new Model();
            quotes_list = new ArrayList<>();
    
            // Event Value Methodes
    
            databaseReference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()){
                        myShayari = dataSnapshot1.getValue(Model.class);
                        if(myShayari != null) {
                            quotes_list.add(myShayari.getTitle());
                        }
                    }
    
                    quotes_txt.setText(quotes_list.get(position));
                    count_txt.setText(position+"/" + quotes_list.size());
                }
    
                @Override
                public void onCancelled(@NonNull DatabaseError error) {
    
                    Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
    
                }
            });
    
    
    
        }
    
        @Override
        public void onClick(View view) {
    
            switch (view.getId()){
                case R.id.backBtn:
                    back();
                    break;
    
                case R.id.copyBtn:
                    copy();
                    break;
    
                case R.id.shareBtn:
                    share();
                    break;
    
                case R.id.nextBtn:
                    next();
                    break;
    
            }
    
        }
    
        @Override
        public boolean onOptionsItemSelected(@NonNull MenuItem item) {
            if (item.getItemId() == android.R.id.home)
                finish();
            return super.onOptionsItemSelected(item);
        }
    
        private void back(){
            if (position>0){
                position = (position -1) % quotes_list.size();
                quotes_txt.setText(quotes_list.get(position));
                count_txt.setText(position + "/" + quotes_list.size());
            }
        }
    
        private void next(){
            position = (position +1) % quotes_list.size();
            quotes_txt.setText(quotes_list.get(position));
            count_txt.setText(position + "/" + quotes_list.size());
        }
    
        private void copy(){
            ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clipData = ClipData.newPlainText("text", quotes_txt.getText());
    
            if (clipboardManager != null){
                clipboardManager.setPrimaryClip(clipData);
            }
            Toast.makeText(getApplicationContext(), "copied", Toast.LENGTH_SHORT).show();
    
        }
    
        private void share(){
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_TEXT,quotes_txt.getText());
            startActivity(Intent.createChooser(intent,"share via"));
        }
    
    }

Ошибку показывает в этих строках
а именно next();

case R.id.nextBtn:
            next();
            break;

вторая ошибка position = (position +1) % quotes_list.size();

private void next(){
        position = (position +1) % quotes_list.size();
        quotes_txt.setText(quotes_list.get(position));
        count_txt.setText(position + "/" + quotes_list.size());
    }

Here are five options for dealing with error Msg 8134 “Divide by zero error encountered” in SQL Server.

First, here’s an example of code that produces the error we’re talking about:

SELECT 1 / 0;

Result:

Msg 8134, Level 16, State 1, Line 1
Divide by zero error encountered.

We get the error because we’re trying to divide a number by zero. Mathematically, this does not make any sense. You can’t divide a number by zero and expect a meaningful result.

To deal with this error, we need to decide what should be returned when we try to divide by zero. For example, we might want a null value to be returned. Or we might want zero to be returned. Or some other value.

Below are some options for dealing with this error.

Option 1: The NULLIF() Expression

A quick and easy way to deal with this error is to use the NULLIF() expression:

SELECT 1 / NULLIF( 0, 0 );

Result:

NULL

NULLIF() returns NULL if the two specified expressions are the same value. It returns the first expression if the two expressions are different. Therefore, if we use zero as the second expression, we will get a null value whenever the first expression is zero. Dividing a number by NULL results in NULL.

Actually, SQL Server already returns NULL on a divide-by-zero error, but in most cases we don’t see this, due to our ARITHABORT and ANSI_WARNINGS settings (more on this later).

Option 2: Add the ISNULL() Function

In some cases, you might prefer to return a value other than NULL.

In such cases, you can pass the previous example to the ISNULL() function:

SELECT ISNULL(1 / NULLIF( 0, 0 ), 0);

Result:

0

Here I specified that zero should be returned whenever the result is NULL.

Be careful though. In some cases, returning zero might be inappropriate. For example, if you’re dealing with inventory supplies, specifying zero might imply that there are zero products, which might not be the case.

Option 3: Use a CASE Statement

Another way to do it is to use a CASE statement:

DECLARE @n1 INT = 20;
DECLARE @n2 INT = 0;

SELECT CASE
    WHEN @n2 = 0
    THEN NULL
    ELSE @n1 / @n2
END

Result:

NULL

Option 4: The SET ARITHABORT Statement

The SET ARITHABORT statement ends a query when an overflow or divide-by-zero error occurs during query execution. We can use it in conjunction with SET ANSI WARNINGS to return NULL whenever the divide-by-zero error might occur:

SET ARITHABORT OFF;
SET ANSI_WARNINGS OFF;
SELECT 20 / 0;

Result:

NULL

Microsoft recommends that you always set ARITHABORT to ON in your logon sessions, and that setting it to OFF can negatively impact query optimisation, leading to performance issues.

Some clients (such as SQL Server Management Studio) set ARITHABORT to ON by default. This is why you probably don’t see the NULL value being returned when you divide by zero. You can use SET ARITHIGNORE to change this behaviour if you prefer.

Option 5: The SET ARITHIGNORE Statement

The SET ARITHIGNORE statement controls whether error messages are returned from overflow or divide-by-zero errors during a query:

SET ARITHABORT OFF;
SET ANSI_WARNINGS OFF;

SET ARITHIGNORE ON;
SELECT 1 / 0 AS Result_1;

SET ARITHIGNORE OFF;
SELECT 1 / 0 AS Result_2;

Result:

Commands completed successfully.
Commands completed successfully.
Commands completed successfully.
+------------+
| Result_1   |
|------------|
| NULL       |
+------------+
(1 row affected)
Commands completed successfully.
+------------+
| Result_2   |
|------------|
| NULL       |
+------------+
Division by zero occurred.

Here, I set ARITHABORT and ANSI_WARNINGS to OFF so that the statement wasn’t aborted due to the error, and NULL is returned whenever there’s a divide-by-zero error.

Note that the SET ARITHIGNORE setting only controls whether an error message is returned. SQL Server returns a NULL in a calculation involving an overflow or divide-by-zero error, regardless of this setting.

In the above example we can see that when ARITHIGNORE is ON, the division by zero error is not returned. When it’s OFF, the division by zero error message is returned.

Понравилась статья? Поделить с друзьями:
  • Помогите найти диету как по
  • Как найти лекарство для собак
  • Как молодому парню найти зрелую
  • Многоножка длиннорукий сэнъун как найти
  • Как правильно составить структурную схему