0:
// 非switch计算法
#include <stdio.h>
int main()
{
float i,j;
char ch; // 四则运算的符号算字符
printf("请输入一个式子:");
scanf("%f %c %f",&i,&ch,&j);
if ( '+' == ch || '-' == ch){ // 在c语言当中,ch是一个字符,所以只能用单引号,双引号表示的是一个收地址
if ( '+' == ch){
printf("结果是%.2f",i+j);
}else {
printf("结果是:%.2f",i-j);
}
}else if ( '*' == ch || '/' == ch){
if ( '/' == ch && j != 0){
printf("结果是%.2f",i/j);
}else if ('*' == ch) {
printf("结果是%.2f",i*j);
}else {
printf("除数不能为0!");
}
}else {
printf("请输入正确的式子!");
}
}
// switch法
#include <stdio.h>
#include <stdbool.h>
int main()
{
float op1, op2;
char ch;
float result;
bool invalid = false;
printf("请输入式子:");
scanf("%f %c %f", &op1, &ch, &op2);
switch (ch)
{
case '-': op2 = -op2; // no break
case '+': result = op1 + op2; break;
case '*': result = op1 * op2; break;
case '/':
if (op2 != 0)
{
result = op1 / op2;
break;
}
else
{
invalid = true;
break;
}
}
if (invalid)
{
printf("除数不能为零!\n");
}
else
{
printf("结果是:%.2f\n", result);
}
return 0;
}
复制
1:
#include <Servo.h>
// 为了方便调用,我们为控制左右电机
// 前进后退的数字引脚进行了宏定义
#define LEFT_MOTO_GO 8
#define LEFT_MOTO_BACK 9
#define RIGHT_MOTO_GO 10
#define RIGHT_MOTO_BACK 11
// ...省略部分代码...
void loop()
{
char ch; // 用于接受命令
switch(ch)
{
case 'g':
digitalWrite(LEFT_MOTO_GO, HIGH);
digitalWrite(LEFT_MOTO_BACK, LOW);
digitalWrite(RIGHT_MOTO_GO, HIGH);
digitalWrite(RIGHT_MOTO_BACK, LOW);
break;
case 'b':
digitalWrite(LEFT_MOTO_GO, LOW);
digitalWrite(LEFT_MOTO_BACK, HIGH);
digitalWrite(RIGHT_MOTO_GO, LOW);
digitalWrite(RIGHT_MOTO_BACK, HIGH);
break;
case 'l':
digitalWrite(LEFT_MOTO_GO, LOW);
digitalWrite(LEFT_MOTO_BACK, LOW);
digitalWrite(RIGHT_MOTO_GO, HIGH);
digitalWrite(RIGHT_MOTO_BACK, LOW);
break;
case 'r':
digitalWrite(LEFT_MOTO_GO, HIGH);
digitalWrite(LEFT_MOTO_BACK, LOW);
digitalWrite(RIGHT_MOTO_GO, LOW);
digitalWrite(RIGHT_MOTO_BACK, LOW);
break;
default:
digitalWrite(LEFT_MOTO_GO, LOW);
digitalWrite(LEFT_MOTO_BACK, LOW);
digitalWrite(RIGHT_MOTO_GO, LOW);
digitalWrite(RIGHT_MOTO_BACK, LOW);
break;
}
// ...省略部分代码...
}