轮流交换三个整型变量a,b,c中的数用C语言
时间: 2023-04-09 19:02:58 浏览: 148
可以使用以下代码实现:
int a = 1, b = 2, c = 3;
int temp;
temp = a;
a = b;
b = c;
c = temp;
这样就可以轮流交换三个整型变量a,b,c中的数了。
相关问题
用三个线程轮流打印a,b,c,打印十次,java
以下是一种可能的实现:
```java
public class PrintABC {
public static void main(String[] args) {
Printer printer = new Printer();
Thread threadA = new Thread(new PrintTask(printer, 'a'), "Thread A");
Thread threadB = new Thread(new PrintTask(printer, 'b'), "Thread B");
Thread threadC = new Thread(new PrintTask(printer, 'c'), "Thread C");
threadA.start();
threadB.start();
threadC.start();
}
private static class Printer {
private char currentChar = 'a';
private int count = 0;
public synchronized void printChar(char c) {
while (c != currentChar) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(c);
currentChar = (char) ('a' + (currentChar - 'a' + 1) % 3);
count++;
if (count == 30) {
// 打印完十次后结束程序
System.exit(0);
}
notifyAll();
}
}
private static class PrintTask implements Runnable {
private final Printer printer;
private final char c;
public PrintTask(Printer printer, char c) {
this.printer = printer;
this.c = c;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
printer.printChar(c);
}
}
}
}
```
该程序中,`Printer`类维护了当前应该打印的字符`currentChar`和已经打印的次数`count`。`printChar`方法是线程安全的,每个线程在调用该方法时会等待当前应该打印的字符是自己的时候才打印,否则就一直等待。打印完一个字符后,`currentChar`会更新为下一个应该打印的字符,并且会唤醒所有等待的线程(因为下一个应该打印的字符可能是其他线程对应的字符)。
在`main`方法中创建了三个`PrintTask`对象,并将它们分别封装在三个线程中启动。每个`PrintTask`对象负责打印对应的字符,打印十次后就结束。
整个程序的关键在于`Printer`类中的`printChar`方法,它保证了每个线程都能按照规定的顺序打印自己的字符。
用简单的c语言写一个10位数码管轮流点亮的代码
以下是一个简单的C程序,通过循环轮流点亮10位数码管:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
int i;
int num[10] = {0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f}; // 数码管显示的数字
unsigned char data[10] = {0xfe, 0xfd, 0xfb, 0xf7, 0xef, 0xdf, 0xbf, 0x7f, 0xbf, 0xdf}; // 数码管的位选信号
while (1) {
for (i = 0; i < 10; i++) {
// 输出段选信号
printf("0x%02x \n", num[i]);
// 输出位选信号,点亮对应数码管
printf("0x%02x \n", data[i]);
sleep(1); // 等待1秒
}
}
return 0;
}
```
在这个程序中,我们使用了两个数组,一个包含了显示数字的编码,另一个包含了位选信号。循环中,我们依次输出每个数码管的数字和对应的位选信号,然后等待1秒钟,以达到轮流点亮的效果。