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
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
14.1k12 gold badges78 silver badges119 bronze badges
answered Oct 1, 2008 at 22:57
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 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
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
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 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
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
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 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
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
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
Stephen85Stephen85
2501 silver badge15 bronze badges
Ошибка — Warning: Division by zero in, как исправить
Ошибка Division by zero, как исправить ошибку Warning: Division by zero in
division by zero это не ошибка при установке игры — это обычное деление на ноль…
- Что означает ошибка Division by zero
- Как исправить ошибку Warning: Division by zero in
Что означает ошибка Division by zero
У нас встретилась вот такая ошибка :
Warning: Division by zero in адрес on line 18
Прежде чем приступать к нашей ошибке — давайте просто попробуем перевести!
Warning: Division by zero — перевод
Переведем данную ошибку с английского и нам сразу станет все ясно!
Warning — предупреждение, сигнал сущ
Division — деление, отдел, раздел, распределение сущ
by — по, посредством предл
zero — ноль сущ
Итого, если мы соберем данную фразу «Warning: Division by zero» на русском, то получим :
Внимание! Ошибка деления на ноль!
как исправить ошибку Warning: Division by zero in
Дл ятого, чтобы исправить ошибку «Warning: Division by zero in» нам понадобится скриншот ошибки, который мы приводили раньше. смотрим на него и видим последнее слово и число, line — это линия в файле, 18 — это номер линии где ошибка.
line 18
И та часть, которая размыта — это адрес, по которому находится файл с ошибкой Warning: Division by zero in
Далее находим данный файл и удаляем ошибку!
Не благодарите, но ссылкой можете поделиться!
COMMENTS+
BBcode
haseki 4 / 4 / 1 Регистрация: 02.11.2013 Сообщений: 164 |
||||
1 |
||||
18.10.2015, 15:55. Показов 3234. Ответов 3 Метки нет (Все метки)
Код программы:
При трассировке на команде idiv DX выдает ошибку деления на ноль.
0 |
Charles Kludge Клюг 7673 / 3188 / 382 Регистрация: 03.05.2011 Сообщений: 8,380 |
||||
18.10.2015, 16:35 |
2 |
|||
Что не так в программе? DX используется командой idiv для хранения остатка, поэтому при делении на DX результат непредсказуем.
1 |
4 / 4 / 1 Регистрация: 02.11.2013 Сообщений: 164 |
|
18.10.2015, 16:47 [ТС] |
3 |
Charles Kludge, огромное спасибо, все понятно!
0 |
Ушел с форума 15881 / 7457 / 1010 Регистрация: 11.11.2010 Сообщений: 13,441 |
|
20.10.2015, 03:47 |
4 |
idiv DX выдает ошибку деления на ноль haseki,
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.