C/C++ 棘手程序
以下是 10 个棘手程序,它们将测试您的编程基础知识。
1. 用 C++ 打印"“ ” 的程序
在 C++ 编程语言中,我们使用引号来表示要打印的文本的开始和结束。因此,打印引号"需要特殊的转义序列。因此,我们将使用 \” 在 C++ 中打印引号。
示例
#include<iostream> using namespace std; int main() { cout<<"\"Tutorials Point \""; return 0; }
输出
"Tutorials Point "
2. 使用循环或 goto 语句打印从 1 到 10 的数字的程序
在编程中多次迭代同一代码块时,有几种方法。它们是 −
- 使用循环
- 使用 goto 语句
- 使用递归函数
由于您不能使用循环或 goto 语句,因此唯一有效的方法是使用递归函数。让我们看看如何使用递归调用打印从 1 到 10 的数字。
示例
#include <stdio.h> void printNumber(int count){ printf("%d\n", count ); count+=1; if(count<=10) printNumber(count); } int main(){ printNumber(1); return 0; }
输出
1 2 3 4 5 6 7 8 9 10
3. 不使用算术或比较运算符来检查两个数字是否相等
要检查两个数字是否相等,我们可以使用按位异或运算符 (^)。如果两个数字相等,则这些数字的按位异或为 0。现在,让我们在程序中实现这个概念。
示例
#include<iostream> using namespace std; int main(){ int a = 132; int b = 132; if ( (a ^ b) ) cout<<"a 不等于 b"; else cout<<"a 等于 b"; return 0; }
输出
a 等于 b
4. 在 c/c++ 中不使用 a; 打印 “Hello”
在 c/c++ 编程语言中,有一些方法可以在不使用分号的情况下打印某些内容。我们可以通过使用输出方法 printf 的返回类型来实现这一点。c++ 中的 printf 方法返回打印到输出屏幕的字符数。我们可以使用和无需分号即可执行的条件语句。
示例
#include <stdio.h> int main(){ if(printf("Hello ")) return 0; }
输出
Hello
5. 编写程序,在不使用比较运算符的情况下查找两个数字的最大值和最小值。
要查找不使用比较运算符定义的两个数字的最大值和最小值,我们将使用 abs 方法,并将两个数字的差值传递给它。它将返回数字之间的正差,我们将减去这个绝对差来找到两个给定数字的最大值和最小值。
示例
#include<iostream> using namespace std; int main (){ int x = 15, y = 20; cout<<"The numbers are x = "<<x<<"and y = "<<y<<endl; cout<<"The max of the numbers is "<<((x + y) + abs(x - y)) / 2<<endl; cout<<"The min of the numbers is "<<((x + y) - abs(x - y)) / 2<<endl; return 0; }
输出
The numbers are x = 15and y = 20 The max of the numbers is 20 The min of the numbers is 15
6.打印程序的源代码和输出
将程序的源代码作为同一程序的输出进行打印是一个有点棘手的问题,需要对编程语言有相当好的理解才能做到。
在这个程序中,我们将使用文件处理的概念,打开我们用来编写代码的同一个文件,然后打印文件的内容。
示例
#include <stdio.h> int main(void){ FILE *program; char ch; program = fopen(__FILE__, "r"); do{ ch=fgetc(program); printf("%c", ch); } while(ch!=EOF); fclose(program); return 0; }
7. 不使用 + 运算符求两个数之和的程序
不使用 + 运算符,只需在代码中多次使用 - 运算符,即可求出两个数之和。以下程序显示了如何操作。
示例
#include<iostream> using namespace std; int main(){ int x = 5; int y = 5; int sum = x - (-y); cout<<"这些数字是 x = "<<x<<" y = "<<y<<endl; cout<<"他们的总和 = "<<sum; return 0; }
输出
这些数字是 x = 5 y = 5 他们的总和 = 10
8.不使用算术或关系运算符来检查给定的数字是否为偶数。
要检查给定的数字是否为偶数,我们可以使用按位运算符。按位 & 运算符与 0x01 一起将检查数字中第 0 位的位置。如果第 0 位的位为 1,则数字为奇数,否则为偶数。
示例
#include<iostream> using namespace std; int main(){ int a = 154; if(a & 0x01) { cout<<a<<" 为奇数"; } else{ cout<<a<<" 为偶数"; } printf("\n"); return 0; }
输出
154 为偶数
9. 编写不使用 / 运算符将数字除以 4 的程序。
要在不使用除法运算符的情况下将数字除以 4,我们可以使用右移位运算符 >> 来移动最后一位。
示例
#include<iostream> using namespace std; int main(){ int n = 128; cout<<n<<"除以 4 = "; n = n >> 2; cout<< n; return 0; }
输出
128 除以 4 = 32
10.C++ 程序递归计算一个数字的各位数字之和,直到它变成个位数。
通过将数字的所有数字相加来计算递归和,然后查看它是否为个位数,则停止,否则重新计算和,直到和变为个位数。
示例
#include <iostream> using namespace std; int main() { int a = 534; int sum; if(a) sum = a % 9 == 0 ? 9 : a % 9 ; else sum = 0; cout<<"最终总和为"<<sum; return 0; }
输出
最终总和为 3