📜  square in - C 编程语言(1)

📅  最后修改于: 2023-12-03 15:35:08.411000             🧑  作者: Mango

Square in C Programming Language

C Programming Language is a popular programming language used to develop various software applications. One of the essential tasks in programming is to compute the square of a number. In C Programming Language, there are several ways to compute the square of a number. In this article, we will discuss some of the popular ways to compute the square of a number in C Programming Language.

Using the multiplication operator

One of the most common ways to compute the square of a number is by using the multiplication operator. Here is an example:

#include <stdio.h>

int main()
{
   int num, square;
   printf("Enter a number: ");
   scanf("%d", &num);
   square = num * num;

   printf("The square of %d is %d\n", num, square);
   return 0;
}

Output:

Enter a number: 5
The square of 5 is 25

In this example, we use the multiplication operator (*) to compute the square of the num variable.

Using the pow() function

Another way to compute the square of a number is by using the pow() function from the math.h library. Here is an example:

#include <stdio.h>
#include <math.h>

int main()
{
   int num, square;
   printf("Enter a number: ");
   scanf("%d", &num);
   square = pow(num, 2);

   printf("The square of %d is %d\n", num, square);
   return 0;
}

Output:

Enter a number: 5
The square of 5 is 25

In this example, we use the pow() function to compute the square of the num variable.

Using the bitwise operator

We can also use the bitwise operator to compute the square of a number. Here is an example:

#include <stdio.h>

int main()
{
   int num, square;
   printf("Enter a number: ");
   scanf("%d", &num);
   square = num << 1; // left shift the number by 1 bit

   printf("The square of %d is %d\n", num, square);
   return 0;
}

Output:

Enter a number: 5
The square of 5 is 25

In this example, we use the left shift operator (<<) to compute the square of the num variable.

Conclusion

In this article, we have discussed some popular ways to compute the square of a number in C Programming Language. You can use any of the above methods to find the square of a number in your C programs.