Как преобразовать integer в string pascal
Перейти к содержимому

Как преобразовать integer в string pascal

  • автор:

Перевод числа из string в integer

Итак, нужно перевести переменную с типом данных string в переменную с типом данных integer. Переменную вводит пользователь, поэтому нужно учитывать спорные моменты. (Обычно переменная это число). Все бы ничего, но это все нужно сделать с помощью процедуры и никак иначе.(Без val, ord и т.д)

procedure (s_per:string; var n_per: longint; var er:byte;);

Лучшие ответы ( 1 )
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
Ответы с готовыми решениями:

Вывести двоичный код вводимого числа(integer) и наоборот из двоичного в integer.
Напишите плиззз программу, которая выводит двоичный код вводимого числа(integer) и наоборот из.

Напишите функцию function count(x:integer):integer;, которая вычисляет количество цифр числа
Напишите функцию function count(x:integer):integer;, которая вычисляет количество цифр числа. .

Из Integer в String
Не могу понять проблему. Задача такая, если в строке не пробел, то записываем в новую строку. Если.

Приведение типов String к Integer
var a1,a2,i:integer; s,s1,s2:string; begin read(s); for i:=1 to length(s) do begin if i=1.

1754 / 1346 / 1407
Регистрация: 28.10.2016
Сообщений: 4,267
Вроде этого?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
procedure StrToNum(s:string; var n:longint); var i:byte; b:boolean; begin b:=true; for i:=1 to length(s) do if not (s[i] in ['0'..'9']) then b:=false; if b then begin n:=StrToInt(s); write('Число: ',n); end else write('Строка содержит недопустимые символы!'); end; var n:longint; s:string; begin readln(s); StrToNum(s,n); end.

Регистрация: 13.04.2017
Сообщений: 27
А почему StrToNum и StrToInt, можно ли их заменить на любую букву ?

Эксперт Pascal/Delphi

6809 / 4566 / 4819
Регистрация: 05.06.2014
Сообщений: 22,438
ElectronicZ, названия самопальных функций даёт сам программист.
Супер-модератор

Эксперт Pascal/DelphiАвтор FAQ

32792 / 21132 / 8144
Регистрация: 22.10.2011
Сообщений: 36,393
Записей в блоге: 8

Лучший ответ

Сообщение было отмечено ZX Spectrum-128 как решение

Решение

Просили же без стандартных процедур/функций конвертации:

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
procedure convert(s : string; var n : longint; var err : byte); var i : integer; begin n := 0; err := 0; for i := 1 to length(s) do if s[i] in ['0' .. '9'] then n := 10 * n + Ord(s[i]) - Ord('0') else begin err := i; break; end; end; var s : string; n : longint; b : byte; begin readln(s); convert(s, n, b); // вывод сообщений к процедуре конвертации не имеет никакого сообщения, поэтому // выносим его в основную часть программы. Задача процедуры - только сконвертировать // строку в число, и вернуть признак ошибки, если она была. if b = 0 then writeln('Число = ', n) else writeln('Ошибка при конвертации в символе № ', b); end.

Как преобразовать тип «integer» в тип «string»?

Преобразовать тип String в Integer
Подскажите плиз как преобразовать тип String в Integer?

Нельзя преобразовать тип integer к string
var game: record const v_main: integer = 1; const v_sub: integer = 0; const.

Нельзя преобразовать тип string к integer
В выделенной 39-й строке выдает ошибку "Нельзя преобразовать тип string к integer". Помогите.

Какой функцией можно преобразовать тип byte в тип string и наоборот?
Вот моя проблема, у меня конченое действие будет выводить число в 10 С.С и в типе byte, а мне надо.

79 / 49 / 23
Регистрация: 15.07.2018
Сообщений: 255
число.ToString

Эксперт Python

1354 / 651 / 207
Регистрация: 23.03.2014
Сообщений: 3,057
Пс, можно так:

1 2 3 4 5 6 7 8
var s:string; i:integer; begin; Randomize; i:=Random(10); str(i,s); write(s); end.

256 / 148 / 70
Регистрация: 29.07.2018
Сообщений: 1,191
Get_Over_Here, можно пример?
Если это типа:

1 2 3 4 5 6
var i:integer; s:string Begin s:='2'; i:=s.ToString; End.

Добавлено через 54 секунды
Dax, хорошо,попробую,потом отпишу)

5067 / 2638 / 2349
Регистрация: 10.12.2014
Сообщений: 10,004

Лучший ответ

Сообщение было отмечено Пс как решение

Решение

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

Если это типа:

Это обратное преобразование строк в число!
i := StrToInt(s); /// Строку в целое число
s := IntToStr(i); /// Целое число в строку

256 / 148 / 70
Регистрация: 29.07.2018
Сообщений: 1,191
JuriiMW, этот способ тоже проверю,потом отпишу)

Эксперт Python

1354 / 651 / 207
Регистрация: 23.03.2014
Сообщений: 3,057
Пс, В вашем примере ошибка

1 2 3 4 5 6
var i:integer; s:string Begin s:='2'; i:=s.ToString; End.

Добавлено через 8 минут
А тут, i- случайное псевдослучайное число

1 2 3 4 5 6 7 8
var s:string; i:integer;// integer; begin; Randomize; i:=Random(10); str(i,s);// str- приводжит его к сроке write(s); end.

Добавлено через 5 минут

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

,кавычки же)
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
Помогаю со студенческими работами здесь

Нельзя преобразовать тип function(n: integer): integer к integer
Function F(n:integer): integer; var i, c:integer; begin c:=0; for i:= 1 to 1000 do begin .

Ошибка : Нельзя преобразовать тип array [1..8] of integer к integer
Дана целочисленная матрица В размером 5х8. Получить массив С из 0 и 1, в котором Ci=1, если в i –ой.

Нельзя преобразовать тип integer к array [1.8] of integer
Естественное слияние.pas(116) : Нельзя преобразовать тип integer к array of integer program cal;.

Нельзя преобразовать тип array [1.10] of integer к integer
Не робит код в этом месте( uses GraphABC; . var v: array of Picture; x2,y2: array of.

Нельзя преобразовать тип array [1.10] of integer к integer
Пытаюсь преобразовать программный код Mathcad в Паскаль Тут же выходит ошибка, — Нельзя.

Невозможно преобразовать тип function от integer к integer
Выдает ошибку.В строке 17 невозможно преобразовать тип function от integer к integer. Как.

PascalABC.Net Нельзя преобразовать тип integer к string

День добрый! Я школьник. Начал проходит Pascal.
Выдает ошибку: Нельзя преобразовать тип integer к string.

a:= StrToInt(a); ( не нравится ему эта строчка)

В чём дело? Мне нужно string в integer. Как мне это сделать? Помогите!

Лучший ответ

изначально переменная а — строковая

а ты в неё пытаешься запихать число

сделай две переменные, одну числовую, другую — строковую

Ы ыУченик (120) 9 лет назад
СПАСИБО! ВСЕ РАБОТАЕТ! УРААА!)
Остальные ответы

Ну ты меня убил чувак 🙂 Вот Этими словами — (Я школьник. Начал проходит Pascal.Выдает ошибку: Нельзя преобразовать тип integer к string.)
А первые два урока чем занимался? Когда про типы данных рассказывали?.

Борис СероусовЗнаток (335) 6 лет назад
Ты, наверное, профи потому, что малышей троллишь? Объяснил бы лучше, чем выделываться.
Похожие вопросы
Ваш браузер устарел

Мы постоянно добавляем новый функционал в основной интерфейс проекта. К сожалению, старые браузеры не в состоянии качественно работать с современными программными продуктами. Для корректной работы используйте последние версии браузеров Chrome, Mozilla Firefox, Opera, Microsoft Edge или установите браузер Atom.

Int to String in Java – How to Convert an Integer into a String

Ihechikara Vincent Abba

Ihechikara Vincent Abba

Int to String in Java – How to Convert an Integer into a String

You can convert variables from one data type to another in Java using different methods.

In this article, you’ll learn how to convert integers to strings in Java in the following ways:

  • Using the Integer.toString() method.
  • Using the String.valueOf() method.
  • Using the String.format() method.
  • Using the DecimalFormat class.

How to Convert an Integer to a String in Java Using Integer.toString()

The Integer.toString() method takes in the integer to be converted as a parameter. Here’s what the syntax looks like:

Integer.toString(INTEGER_VARIABLE)

Here’s an example:

class IntToStr < public static void main(String[] args) < int age = 2; String AGE_AS_STRING = Integer.toString(age); System.out.println("The child is " + AGE_AS_STRING + " years old"); // The child is 2 years old >>

In the example above, we created an integer – age – and assigned a value of 2 to it.

To convert the age variable to a string, we passed it as a parameter to the Integer.toString() method: Integer.toString(age) .

We stored this new string value in a string variable called AGE_AS_STRING .

We then concatenated the new string variable with other strings: «The child is » + AGE_AS_STRING + » years old» .

But, would an error be raised if we just concatenated the age variable to these other strings without any sort of conversion?

class IntToStr < public static void main(String[] args) < int age = 2; System.out.println("The child is " + age + " years old"); // The child is 2 years old >>

The output above is the same as the example where we had to convert the integer to a string.

So how do we know if the type conversion actually worked?

We can check variable types using the Java getClass() object. That is:

class IntToStr < public static void main(String[] args) < int age = 2; String AGE_AS_STRING = Integer.toString(age); System.out.println(((Object)age).getClass().getSimpleName()); // Integer System.out.println(AGE_AS_STRING.getClass().getSimpleName()); // String >>

Now we can verify that when the age variable was created, it was an Integer , and after type conversion, it became a String .

How to Convert an Integer to a String in Java Using String.valueOf()

The String.valueOf() method also takes the variable to be converted to a string as its parameter.

class IntToStr < public static void main(String[] args) < int age = 2; String AGE_AS_STRING = String.valueOf(age); System.out.println("The child is " + AGE_AS_STRING + " years old"); // The child is 2 years old >>

The code above is similar to that in the last section:

  • We created an integer called age .
  • We passed the age integer as a parameter to the String.valueOf() method: String.valueOf(age) .

You can also check to see if the type conversion worked using the getClass() object:

System.out.println(((Object)age).getClass().getSimpleName()); // Integer System.out.println(AGE_AS_STRING.getClass().getSimpleName()); // String

How to Convert an Integer to a String in Java Using String.format()

The String.format() method takes in two parameters: a format specifier and the variable to be formatted.

Here’s an example:

class IntToStr < public static void main(String[] args) < int age = 2; String AGE_AS_STRING = String.format("%d", age); System.out.println("The child is " + AGE_AS_STRING + " years old"); // The child is 2 years old >> 

In the example above, we passed in two parameters to the String.format() method: «%d» and age .

«%d» is a format specifier which denotes that the variable to be formatted is an integer.

age , which is the second parameter, will be converted to a string and stored in the AGE_AS_STRING variable.

You can also check the variable types before and after conversion:

System.out.println(((Object)age).getClass().getSimpleName()); // Integer System.out.println(AGE_AS_STRING.getClass().getSimpleName()); // String

How to Convert an Integer to a String in Java Using DecimalFormat

The DecimalFormat class is used for formatting decimal numbers in Java. You can use it in different ways, but we’ll be using it to convert an integer to a string.

Here’s an example:

import java.text.DecimalFormat; class IntToStr < public static void main(String[] args) < int age = 2; DecimalFormat DFormat = new DecimalFormat("#"); String AGE_AS_STRING = DFormat.format(age); System.out.println("The child is " + AGE_AS_STRING + " years old"); // The child is 2 years old System.out.println(((Object)age).getClass().getSimpleName()); // Integer System.out.println(AGE_AS_STRING.getClass().getSimpleName()); // String >>

Let’s break the code down:

  • To be able to use the DecimalFormat class in the example above, we imported it: import java.text.DecimalFormat; .
  • We created the integer age variable.
  • We then created a new object of the DecimalFormat class called DFormat .
  • Using the object’s format() method, we converted age to a string: DFormat.format(age); .

Summary

In this article, we talked about converting integers to strings in Java.

We saw examples that showed how to use three different methods – Integer.toString() , String.valueOf() , String.format() — and the DecimalFormat class to convert variables from integers to strings.

Each example showed how to check the data type of a variable before and after conversion.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *