Нельзя преобразовать тип boolean к integer как исправить

Нельзя преобразовать тип boolean к integer PascalABC.NET Решение и ответ на вопрос 2563488

В городе, в котором живут друзья Андрей и Борис, метро состоит из единственной кольцевой линии, вдоль которой на равном расстоянии друг от друга расположены n станций, пронумерованных от 1 до n. Участок линии метро между двумя соседними станциями называется перегоном.

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

Друзья заметили, что выполняется следующее условие: если загадать некоторую станцию X и выписать для нее два числа: Da — расстояние от станции, на которой живет Андрей, до станции X и Db — расстояние от станции, на которой живет Борис, до станции X, то полученная пара чисел [Da, Db] будет однозначно задавать станцию X.

Например, если n = 4, Андрей живет на станции 1, а Борис живет на станции 2, то станция 1 задается парой [0, 1], станция 2 — парой [1, 0], станция 3 — парой [2, 1] и станция 4 — парой [1, 2].

Их одноклассник Сергей живет в соседнем городе и не знает, на каких станциях живут Андрей и Борис. Чтобы найти друзей, он заинтересовался, сколько существует вариантов пар станций A, B, таких что если Андрей живет на станции A, а Борис — на станции B, то выполняется описанное выше условие.

Требуется написать программу, которая по числу станций n на кольцевой линии определяет искомое количество вариантов.

Входные данные
Первая строка входного файла содержит одно целое число n (3 ≤ n ≤ 40 000).

Выходные данные
Выходной файл должен содержать одно число — искомое количество вариантов.

Пояснения к примерам
В первом примере подходят следующие варианты:
* Андрей живет на станции 1, а Борис на станции 2;
* Андрей живет на станции 1, а Борис на станции 4;
* Андрей живет на станции 2, а Борис на станции 1;
* Андрей живет на станции 2, а Борис на станции 3;
* Андрей живет на станции 3, а Борис на станции 2;
* Андрей живет на станции 3, а Борис на станции 4;
* Андрей живет на станции 4, а Борис на станции 1;
* Андрей живет на станции 4, а Борис на станции 3.

Примеры
входные данные
4
выходные данные
8
входные данные
5
выходные данные
20

Условие задачи

The error means exactly what it says — you’re trying to assign a boolean value to an integer, which doesn’t make sense. What’s the integer value of true? That’s like asking «what variety of apple is this orange?» However, you have other bugs as well — see my comments below.

double int dFirst;

There’s no such thing as «double int.» A double is a real number and an int is an integer, and obviously a number can’t be both an integer and a real number.

    int iSecond;
    int iThird;

    Console.WriteLine("Enter a number between 1 and 10: ");
    dFirst = Convert.ToInt32(Console.ReadLine());

This’ll cause the program to crash if they enter something that’s not a number. It also doesn’t check to make sure that the user entered something between 1 and 10. Try something like the following:

        int intResult;
        // Prompt the user for an input until they enter a number between 1 - 10
        while (!int.TryParse(Console.ReadLine(), out intResult) || intResult < 1 || intResult > 10)
        {
            Console.WriteLine("Not a valid int - try again");
        }

The following code has the same exact problem:

    Console.WriteLine("Enter another number between 1 and 10: ");
    iSecond = Convert.ToInt32(Console.ReadLine());

    if (dFirst > iSecond)
    {
        Console.WriteLine("The first number is bigger than the second one you entered.");
    }
    else if (iSecond >= dFirst)
    {
        Console.WriteLine("These numbers are equal");

No, not necessarily — iSecond could be greater than dFirst. I assume you meant == here.

    }
    else (iSecond >= dFirst)

This should either be «else if» or simply «else.» In this case, you can just do «else» — if first isn’t greater than second and they’re not equal, then obviously second has to be larger. Also, this condition is exactly the same as the previous condition, so there’s absolutely no way that this condition can ever be met. Consider the following:

if (someCondition) {
   // ...
 }
// The following condition quite literally means "if not someCondition and someCondition," so obviously this couldn't possibly run.
else if (someCondition) { 
    // ...
 }

Recall that «else if» means «if the previous conditions are false and the conditions I specify here are true.»

            {
        iThird = dFirst <= iSecond;

This is what’s causing the error. I assume you meant something kind of like:

iThird = dFirst <= iSecond ? iSecond : dFirst;

This will assign the larger number to iThird, but you can make it whatever you want.

        Console.WriteLine("The number is: " + iThird);

        Console.WriteLine();
        Console.WriteLine("Press any key to close.");
        Console.ReadKey();

    }

  • Remove From My Forums
  • Question

  • Hello, I’m just starting the programing thing now and I already have problems… I was just practicing some stuff learned from books and tutorials online and got stuck when got the message.

    Im trying to display a box whenever the user does not type anything on the textbox. the lines in bold are the ones giving me the error. thanks.

    public partial class Form1 : Form

        {

            public Form1()

            {

                InitializeComponent();

            }

            int answer = 0;

            int loopStart;

            int loopEnd;

            int multiply;

            int noValue = 0;

            private void btnLoop_Click(object sender, EventArgs e)     

            {

                loopStart = int.TryParse(txtbox1.Text, out noValue);

                loopEnd = int.TryParse(txtbox2.Text, out noValue);

                multiply = int.TryParse(txtBox3.Text, out noValue);

                listBox1.Items.Clear(); 

                for (int i = loopStart; i < loopEnd; i++)

                {

                    answer = multiply * i;

                    listBox1.Items.Add(«i= «+i +» answer = » + answer.ToString());

                }

            }

Answers

  • Check out http://msdn.microsoft.com/en-us/library/f02979c7.aspx
    TryParse returns a boolean (true or false) to the caller to verify whether an integer was parsed.  Your answer that you want is actually in the «noValue» variable.  When you are assigning this boolean value to your integer variable (in any of the three cases actually) the complier is complaining.

    So if you had a situation where you wanted to see if a parsed value came back via the noValue you could use

    if(int.TryParse(txtbox1.Text,out noValue))
    //ok, I’ve got one now what
    else
    //there was a problem parsing an integer out of that particular text

    • Proposed as answer by

      Monday, September 7, 2009 7:10 AM

    • Marked as answer by
      DarkLuis
      Monday, September 7, 2009 3:55 PM

  • Remove From My Forums
  • Question

  • Hi
    I get an error:
    Cannot implicitly convert type ‘bool’ to ‘int’
    anyway the program executes with the errors but I dont know how to fix it.
    Here is the code snippet:

    // switch on the value of inputInt
                    switch (inputInt)
                    {
                        case (inputInt == 0):
                            Console.WriteLine("your input is zero.");
                            goto repeat;
                        case (inputInt % 2 != 0):
                            Console.WriteLine("your input is odd.");
                            goto repeat;
                        case (inputInt % 2 == 0):
                            Console.WriteLine("your input is even.");
                            goto repeat;
                        case (inputInt % 10 == 0):
                            Console.WriteLine("your input is a multiple of 10.");
                            goto repeat;
                        case (inputInt > 100):
                            Console.WriteLine("your input is too large (input>100).");
                            goto repeat;
                    }

    I do not understand what is the problem. Can’t we have formulas and equations into the case statement?
    Best regards

Answers

  • No, a switch statement requires that case labels are constants: this allows the compiler to produce highly efficient code that doesn’t have to evaluate all the possible comparisons.

    Since in this case you actually need every single case to be evaluated, the switch statement is not appropriate. You could probably use an if-else chain:

    if (input % 2 == 0) {
      …
    } else if (input % 2 != 0) {
      …
    } else if (input % 2 == 0) {
      …
    } else …

    And don’t use goto… there are almost certainly much better alternatives.

    HTH
    —mc

    • Marked as answer by

      Thursday, March 18, 2010 6:34 AM

  • The problem is you can’t do conditional checks in a case statement declaration.

    The point of a case in a switch statement is to only occur when a static value is true. IE: 

    int x = 0;

    switch(x)

    {

       case (0):

         break;

       case (1):

         break;

    You can’t have a conditional check in a case statement.


    Blog (WPF/C#)

    Crystal (WPF Google Contact UI/C# Library)

    • Marked as answer by
      Liliane Teng
      Thursday, March 18, 2010 6:35 AM

  • It doesn’t run…its running an old version VS Studio can be told to stop doing that when errors exist.

    The problem is that the switch needs a value specified before compilation. The act of doing something line (inputInt% 2) is a runtime action. The compiler cannot predict what is going to happen; hence the error.

    You need to break your logic away from the switch into if/else and avoid the switch for this situation.

    Why Bool? What happens is that the parenthesis in case ((xxxx = yyyy) == 0)  are looked at by the copiler and the result is a bool right? Then it looks at the switch (inputInt) which is an int. Hence an int cannot be converted to abool.

    HTH


    William Wegerson (www.OmegaCoder.Com)

    • Marked as answer by
      Liliane Teng
      Thursday, March 18, 2010 6:37 AM

  • Set key to -1

    int key = -1;

    and use the default or catch it as case -1.


    William Wegerson (www.OmegaCoder.Com)

    • Marked as answer by
      Liliane Teng
      Thursday, March 18, 2010 6:33 AM

    • Marked as answer by
      Liliane Teng
      Thursday, March 18, 2010 6:33 AM
  • Remove From My Forums
  • Question

  • Hi
    I get an error:
    Cannot implicitly convert type ‘bool’ to ‘int’
    anyway the program executes with the errors but I dont know how to fix it.
    Here is the code snippet:

    // switch on the value of inputInt
                    switch (inputInt)
                    {
                        case (inputInt == 0):
                            Console.WriteLine("your input is zero.");
                            goto repeat;
                        case (inputInt % 2 != 0):
                            Console.WriteLine("your input is odd.");
                            goto repeat;
                        case (inputInt % 2 == 0):
                            Console.WriteLine("your input is even.");
                            goto repeat;
                        case (inputInt % 10 == 0):
                            Console.WriteLine("your input is a multiple of 10.");
                            goto repeat;
                        case (inputInt > 100):
                            Console.WriteLine("your input is too large (input>100).");
                            goto repeat;
                    }

    I do not understand what is the problem. Can’t we have formulas and equations into the case statement?
    Best regards

Answers

  • No, a switch statement requires that case labels are constants: this allows the compiler to produce highly efficient code that doesn’t have to evaluate all the possible comparisons.

    Since in this case you actually need every single case to be evaluated, the switch statement is not appropriate. You could probably use an if-else chain:

    if (input % 2 == 0) {
      …
    } else if (input % 2 != 0) {
      …
    } else if (input % 2 == 0) {
      …
    } else …

    And don’t use goto… there are almost certainly much better alternatives.

    HTH
    —mc

    • Marked as answer by

      Thursday, March 18, 2010 6:34 AM

  • The problem is you can’t do conditional checks in a case statement declaration.

    The point of a case in a switch statement is to only occur when a static value is true. IE: 

    int x = 0;

    switch(x)

    {

       case (0):

         break;

       case (1):

         break;

    You can’t have a conditional check in a case statement.


    Blog (WPF/C#)

    Crystal (WPF Google Contact UI/C# Library)

    • Marked as answer by
      Liliane Teng
      Thursday, March 18, 2010 6:35 AM

  • It doesn’t run…its running an old version VS Studio can be told to stop doing that when errors exist.

    The problem is that the switch needs a value specified before compilation. The act of doing something line (inputInt% 2) is a runtime action. The compiler cannot predict what is going to happen; hence the error.

    You need to break your logic away from the switch into if/else and avoid the switch for this situation.

    Why Bool? What happens is that the parenthesis in case ((xxxx = yyyy) == 0)  are looked at by the copiler and the result is a bool right? Then it looks at the switch (inputInt) which is an int. Hence an int cannot be converted to abool.

    HTH


    William Wegerson (www.OmegaCoder.Com)

    • Marked as answer by
      Liliane Teng
      Thursday, March 18, 2010 6:37 AM

  • Set key to -1

    int key = -1;

    and use the default or catch it as case -1.


    William Wegerson (www.OmegaCoder.Com)

    • Marked as answer by
      Liliane Teng
      Thursday, March 18, 2010 6:33 AM

    • Marked as answer by
      Liliane Teng
      Thursday, March 18, 2010 6:33 AM

Неописанная переменная

begin
  S := 1; // Неизвестное имя S
end.

Все используемые переменные должны быть предварительно описаны с помощью ключевого слова var (внутри блока begin/end или, что обычно хуже, в разделе описаний вначале программы).

Отсутствующая ;

begin
  var S: integer 
  S := 1;         // Компилятор здесь скажет: Ожидалась ; — имеется ввиду предыдущая строка!
end.
begin
  var S := 1 
  S := S + 1  // Аналогично: проблема на предыдущей строке, а на текущей нет, потому что после неё идёт end.
end.

Очень частая ошибка у начинающих. Курсор, как правило, позиционируется в начале следующей строки.

Несовместимость типов при присваивании

begin
  var S: integer := 1.3; // Нельзя преобразовать тип real к integer
end.

Безболезненно можно присваивать только данные одного типа. Если данные — разных типов, то в редких случаях можно преобразовать данные одного типа в данные другого. Например, целое можно преобразовать в вещественное, а символ — в строку. Обратные преобразования не допускаются.

Чтобы не ошибаться в подобных простых случаях в Паскале есть следующая краткая форма объявления и инициализации переменной:

begin
  var S := 1.3; // Тип real будет выведен компилятором автоматически
end.

Отсутствие закрывающего апострофа литеральной строки

begin
  var x := 2;   // x получает тип integer
  var y := 3;   // y получает тип integer
  writeln('Результат сложения равен =, x + y); // Не хватает закрывающего апострофа
end.

Закрыть апостроф надо на той же строке, где расположен открывающий апостроф

Ошибки расстановки запятых и апострофов при выводе строк и выражений

begin
  var x := 2;   // x получает тип integer
  var y := 3;   // y получает тип integer
  writeln(x, '+,' y, '=', x+y); // Неверная расстановка запятых и апострофов
end.

Слишком много запятых и апострофов рядом, потому начинающие часто путаются  :)
Надо уяснить правила:

  • запятые разделяют разные элементы вывода
  • все, что находится в апострофах, будет выведено на экран без изменений

Ошибка ввода

begin
  var x: integer;
  read(x); // введите блаблабла и посмотрите, что получится
end.

Это — ошибка во время выполнения. Программа пытается преобразовать введенную строку в число, не может это сделать и завершается с ошибкой.

Аналогичный фрагмент в более современном и предпочтительном синтаксисе:

begin
  var x := ReadInteger;
end.

Ошибка неинициализированной переменной

begin
  var x: integer;
  // Забыли инициализировать или ввести x
  var r := x * x;  // r получает тип integer
  writeln('Квадрат числа ', x, ' = ', r);
end.

Перед использованием любую переменную надо ввести или присвоить ей начальное значение. Это действие называется инициализацией переменной.

Деление на 0

begin
  var x := 0;
  var c := 666 div x; // Здесь происходит деление на 0
end.

Если во время выполнения программа выполнит деление на 0, то она завершится с ошибкой.

Корень из отрицательного числа

begin
  writeln(sqrt(-1)); // Корень из отрицательного числа 
end.

В обычном Паскале возникает ошибка времени выполнения.
В PascalABC.NET выводится NaN — Not a Number

Ссылки

  • Программы для начинающих
  • Сайт PascalABC.NET: Программы и алгоритмы для начинающих

GreenSwag

Пользователь

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

Сообщения: 2560

Рейтинг: 1049

GreenSwag

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

Сообщения: 2560

Рейтинг: 1049

Ultimessiah сказал(а):↑

Мдемс… тяжело тебе будет с этим)))

Уже подкорректировал, но выше я описал способ поизящней с IntToStr
var i,n,flag,x,w:integer; y,z:string;
begin
w:=0;
readln(x);
Str(x,y);
i = 1;
n = 4;
flag = false;
while(i<=n) do
begin
z:=copy(y,i,1);
if (z=3) or (z=8) or (z=2) then
begin
flag = true;
exit;
end
end
writeln(flag);
end

Нажмите, чтобы раскрыть…

Program8.pas(8) : Нельзя преобразовать тип boolean к integer

Justskip

Пользователь

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

Сообщения: 278

Рейтинг: 158

Justskip

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

Сообщения: 278

Рейтинг: 158

GreenSwag сказал(а):↑

Program8.pas(8) : Нельзя преобразовать тип boolean к integer

Нажмите, чтобы раскрыть…

Какой курс? Или класс?

Ultimessiah

Пользователь

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

Сообщения: 116

Рейтинг: 88

Ultimessiah

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

Сообщения: 116

Рейтинг: 88

GreenSwag сказал(а):↑

Program8.pas(8) : Нельзя преобразовать тип boolean к integer

Нажмите, чтобы раскрыть…

да уж, чувак тебе надо начать с основ, впрочем решать тебе)
конкретно по ошибке, flag объявлен как int, а засунуть пытаешься значение типа bool, объяви flag как boolean

Ultimessiah

Пользователь

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

Сообщения: 116

Рейтинг: 88

Ultimessiah

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

Сообщения: 116

Рейтинг: 88

Короче вот работающий код)
*Обновил, терь не важно какое число хоть 4х значное хоть 10 значное

var
 a,z:integer;
 flag: boolean;
begin
 a := 1234;
 flag := false;
 while(a>0) do
 begin
   z := a mod 10;
   a := a div 10;
   if ((z=3) or (z=8) or (z=2)) then
   begin
     flag := true;
     Break;
   end;
 end;
 write(flag);
end.

GreenSwag

Пользователь

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

Сообщения: 2560

Рейтинг: 1049

GreenSwag

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

Сообщения: 2560

Рейтинг: 1049

Ultimessiah сказал(а):↑

Короче вот работающий код)
*Обновил, терь не важно какое число хоть 4х значное хоть 10 значное

var
 a,z:integer;
 flag: boolean;
begin
 a := 1234;
 flag := false;
 while(a>0) do
 begin
   z := a mod 10;
   a := a div 10;
   if ((z=3) or (z=8) or (z=2)) then
   begin
     flag := true;
     Break;
   end;
 end;
 write(flag);
end.

Нажмите, чтобы раскрыть…

спс

Ultimessiah

Пользователь

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

Сообщения: 116

Рейтинг: 88

Ultimessiah

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

Сообщения: 116

Рейтинг: 88

Valkrest сказал(а):↑

Можешь пояснить идею?

Нажмите, чтобы раскрыть…

считаем диагонали кирпича ab,bc,ac и диагональ отверстия xy, и если хоть одна из диагоналей кирпича меньше или равна диагонали отверстия кирпич проходит.

Тема закрыта

  • Заголовок

    Ответов Просмотров

    Последнее сообщение

  • Всезнающий Оракл

    Сообщений: 2
    11 Feb 2023 в 21:42

    Молчаливый молчун

  • ПОДДЕРЖиваю из леса

    Сообщений: 1
    11 Feb 2023 в 21:37

    ПОДДЕРЖиваю из леса

  • Максим Тильт

    Сообщений: 3
    11 Feb 2023 в 21:20

    Максим Тильт

  • Всезнающий Оракл

    Сообщений: 6
    11 Feb 2023 в 20:58

    Сообщений:6

    Просмотров:20

    KeltZer

  • Hendrix Hendrix

    Сообщений: 21
    11 Feb 2023 в 20:55

    Сообщений:21

    Просмотров:39

    Hendrix Hendrix

Понравилась статья? Поделить с друзьями:
  • Неправильная форма черепа как исправить
  • Нельзя не отметить обоснованность высказанных замечаний речевая ошибка
  • Неполадки код 43 блютуз как исправить
  • Неправильное согласование слов какая ошибка
  • Неправильная форма ногтей на руках как исправить