Square c что это

от admin

How to Square a Number in C++

When we square a number, we simply multiply it by itself. We have to utilize a header file if we want to get a square of a number. Header files allow us to declare a function with a type placeholder that the compiler will fill in at compile-time based on how the function is used.

In C++, when we need a square of any given number, numerous methods are available. Let’s talk about a few of them:

Find square of a number using Power function

Using the Power function, we may square any value. For it, we will have to include <cmath> library. We must pass the Base value to be squared and the Power value into the function. In C++, the power() function works as a square operator in this instance.

#include<iostream>
#include<cmath>
using namespace std ;

int main ( ) {
int b = 34 ;
int p = 2 ;
float result = pow ( b,p )
cout << "Square = " << result << endl ;
}

The “cmath” library has a predefined function called pow. Therefore, we must integrate this library at the beginning of the code. We declare two variables in the body of the main function. The first variable is defined to store the value of the base. The value here is “34”. The second variable is declared to store a power value that is 2 in this program. These two variables have an integer data type.

Furthermore, we apply the pow() function. We pass two arguments (base value and power value) for this function. It returns the result. The output is stored in a new variable termed ‘result’.

Find square of a number using for loop

If we need to get a square of a value without applying multiplication or division, we must use another logic to get the given value’s square. In the succeeding program, we utilize for loop.

#include<iostream>
using namespace std ;

float Sqr ( float number ) {

for ( int j = 0 ; j < number ; j ++ ) {
a = a + number ;
}

We declare the function sqr(), and its data type is ‘float’. We pass a floating-point number as an argument to this function. Moreover, we utilize a for loop in this instance to add a number. First, we allocate ‘0’ to the variable ‘j’ in the initialization segment. The test condition checks the value of that variable. ‘j<number’ tests the loop every time to see if ‘j’ is less than the given value. ‘j++’ increases the variable ‘j’ every time the loop is implemented.

Generally, any indication can be utilized to increment the loop variable. Once the loop ends, the variable is still defined and holds the value allocated by the latest increment. In the code, we add 20 + 20….Up to 20 times. Therefore, after the addition, 20 square (400) is created. Compiling and running the above program produces this type of output:

Find square of a number using while loop

If we use a while loop to find the square of any number, we will need to include an odd number so that the square is created at the end of the program.

#include <iostream>
using namespace std ;

float Square ( float value )
{
float OddNum = 1.0 ;
float SquareNum = 0.0 ;

value = abs ( value ) ;

while ( value — )
{
SquareNum = SquareNum + OddNum ;
OddNum = OddNum + 2 ;
}

In this instance, after integrating the library ‘#include <iostream>, we define the ‘square’ function. The floating-point value is passed as an argument to this function. Further, we declare variables ‘OddNum’ and ‘SquareNum’ and assign them values. Afterward, we apply the absolute function ‘abs()’ that converts the negative value to the positive when we enter any negative value. We use a while loop.

The compiler first evaluates the test condition when a while statement is implemented. Once the body of the loop is implemented, the condition is assessed again, and if it becomes true, the body of the loop is implemented once again. This procedure continues till the test condition becomes false. Once it is false, the control is passed on to the first statement after the end of the body of a loop. In every evaluation, ‘2’ is added to the value ‘OddNum’ to make it odd.

When the above code is executed, it will give the output shown below:

Conclusion

In this article, we have deliberated three techniques for finding the square of the number in C++. First, we see how we get the square of a number by using the pow() function. Likewise, we utilize the ‘for’ loop and ‘while’ loop for finding the square. By using for loop, we perform the addition of any number. Similarly, we add an odd number by using the while loop to get the square.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.

#define Square(x) (x*(x)) [duplicate]

Can you please explain why the following code outputs «29»?

Dan Dinu's user avatar

5 Answers 5

Since macros only do textual replacement you end up with:

You should absolutely always put macro arguments between parentheses.

Better yet, use a function and trust the compiler to inline it.

As leemes notes, the fact that the macro evaluates x twice can be a problem. Using a function or more complicated mechanisms such as gcc statement expressions can solve this. Here’s a clumsy attempt:

Please note that although the macro

seems to solve the problem, it does not. Consider this:

The preprocessor expands this to:

which is undefined behavior. Some compilers will evaluate this as

which seems as expected in the first place. But x = 7 afterwards, since the increment operator has been applied twice. Clearly not what you were looking for.

This is why macros* are evil.

(*Macros which tend to be used as a replacement for inline-functions.)

You can fix this in C++ using template functions which can handle all types and in C by specifying a concrete type (since even overloading isn’t supported in C, the best you can get is different functions with suffixes):

Читать:
Как узнать аудиокодек realtek

Specifically for GCC, there is another solution, since GCC provides the typeof operator so we can introduce a temporary value within the macro:

Класс Square

Квадрат — это частный случай прямоугольника. Соответствующий класс является потомком класса Rect:

/// Класс Square — потомок класса Rect.

public class Square:Rect

public Square(int side, int x, int y): base(side,side,x,y)

//квадрат — это прямоугольник с равными сторонами

Класс Person

Этот класс является прямым потомком класса Figure. Вместе с тем, класс является клиентом трех других классов семейства — Circle, Rect и LittleCircle, поскольку элементы фигуры, составляющие человечка, являются объектами этих классов%

/// Класс Person — потомок класса Figure,

/// клиент классов Circle, Rect, LittleCircle.

public class Person:Figure

public Person(int head_h, int x, int y): base(x,y)

//head_h — радиус головы, x,y — ее центр.

//остальные размеры исчисляются относительно

head = new Circle(head_h,x,y);

int body_y = y + 3*head_h;

int body_w =2*head_h;

int body_h = 4*head_h;

body = new Rect(body_w, body_h, body_x,body_y);

nose = new LittleCircle(x+head_h +2, y);

public override void Show(System.Drawing.Graphics g,

System.Drawing.Pen pen, System.Drawing.Brush brush)

int h = Convert.ToInt32(head_h*scale);

int top_x = center.X — h;

int top_y = center.Y — h;

g.DrawEllipse(pen, top_x,top_y, 2*h,2*h);

g.FillEllipse(brush, top_x,top_y, 2*h,2*h);

g.DrawRectangle(pen, top_x,top_y, 2*h,4*h);

g.FillRectangle(brush, top_x,top_y, 2*h,4*h);

g.DrawEllipse(pen, top_x,top_y, 8,8);

g.FillEllipse(brush, top_x,top_y, 8,8);

public override System.Drawing.Rectangle

int h = Convert.ToInt32(head_h*scale);

int top_x = center.X — h;

int top_y = center.Y — h;

Список с курсором. Динамические структуры данных

Добавим в проект классы, задающие динамические структуры данных. Конечно, можно было бы воспользоваться стандартными. Но для обучения крайне полезно уметь создавать собственные классы, задающие такие структуры данных. Список с курсором — один из важнейших образцов подобных классов%:

/// Класс TwoWayList(G) описывает двусвязный список с

/// курсором. Элементами списка являются объекты

/// TwoLinkable, хранящие, помимо указателей на двух

/// преемников, объекты типа G.Курсор будет определять /// текущий (активный) элемент списка. Класс будет

How to effectively deal with bots on your site? The best protection against click fraud.

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

В C++, когда нам нужен квадрат любого заданного числа, доступно множество методов. Расскажем о некоторых из них:

Найдите квадрат числа, используя функцию Power

Используя функцию Power, мы можем возвести в квадрат любое значение. Для этого нам нужно будет включить библиотека. Мы должны передать базовое значение, которое нужно возвести в квадрат, и значение мощности в функцию. В C++ функция power() в данном случае работает как квадратный оператор.

#включать
#включать
с использованием пространство имен стандарт ;

инт основной ( ) <
инт б = 34 ;
инт п = 2 ;
плавать результат = паф ( б, р )
cout << «Квадрат » src=»https://ciksiti.com/f/3390c6eb9765b5abe22edb9bdc796781.png»>

В библиотеке cmath есть предопределенная функция pow. Поэтому мы должны интегрировать эту библиотеку в начале кода. Мы объявляем две переменные в теле основной функции. Первая переменная определена для хранения значения базы. Значение здесь равно «34». Вторая переменная объявлена ​​для хранения значения мощности, равного 2 в этой программе. Эти две переменные имеют целочисленный тип данных.

Кроме того, мы применяем функцию pow(). Мы передаем два аргумента (базовое значение и значение мощности) для этой функции. Он возвращает результат. Результат сохраняется в новой переменной под названием «результат».

Найти квадрат числа с помощью цикла for

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

плавать площадь ( плавать количество ) <

плавать а = 0.0 ;
для ( инт Дж = 0 ; Дж < количество ; Дж ++ ) <
а = а + количество ;
>

инт основной ( ) <
cout << «Квадрат » src=»https://ciksiti.com/f/d20cf6aa9347216d3960da1b9973bcd2.png»>

Мы объявляем функцию sqr(), и ее тип данных — float. Мы передаем число с плавающей запятой в качестве аргумента этой функции. Кроме того, в этом случае мы используем цикл for для добавления числа. Во-первых, мы выделяем «0» переменной «j» в сегменте инициализации. Условие проверки проверяет значение этой переменной. ‘j

Как правило, любое указание может быть использовано для увеличения переменной цикла. После завершения цикла переменная все еще определена и содержит значение, присвоенное последним приращением. В коде складываем 20+20….до 20 раз. Следовательно, после сложения получается 20 квадратов (400). Компиляция и запуск вышеуказанной программы дает следующий тип вывода:

Найти квадрат числа с помощью цикла while

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

плавать Квадратный ( плавать стоимость )
<
плавать Нечетное число = 1.0 ;
плавать SquareNum = 0.0 ;

стоимость = пресс ( стоимость ) ;

пока ( стоимость — )
<
SquareNum = SquareNum + Нечетное число ;
Нечетное число = Нечетное число + 2 ;
>

вернуть SquareNum ;
>
инт основной ( )
<
cout << «Квадрат числа » src=»https://ciksiti.com/f/d1cb2a8fab55dc457d1c691a9255be0d.png»>

В этом случае после интеграции библиотеки #include , мы определяем функцию «квадрат». Значение с плавающей запятой передается в качестве аргумента этой функции. Далее объявляем переменные OddNum и SquareNum и присваиваем им значения. После этого мы применяем абсолютную функцию «abs()», которая преобразует отрицательное значение в положительное, когда мы вводим любое отрицательное значение. Мы используем цикл while.

Компилятор сначала оценивает тестовое условие, когда реализуется оператор while. Как только тело цикла реализовано, условие оценивается снова, и если оно становится истинным, тело цикла реализуется еще раз. Эта процедура продолжается до тех пор, пока условие проверки не станет ложным. Если оно ложно, управление передается первому оператору после окончания тела цикла. В каждой оценке к значению OddNum добавляется «2», чтобы сделать его нечетным.

Когда приведенный выше код будет выполнен, он выдаст результат, показанный ниже:

Заключение

В этой статье мы обсудили три метода нахождения квадрата числа в C++. Во-первых, мы видим, как мы получаем квадрат числа с помощью функции pow(). Точно так же мы используем цикл for и while для нахождения квадрата. Используя цикл for, мы выполняем сложение любого числа. Точно так же мы добавляем нечетное число, используя цикл while, чтобы получить квадрат.

Похожие статьи