我试图调试一个程序,它是从标准输入中得到值'S'或'P'。我的功能calc_resistance()
需要区分这两种情况,以及既没有输入'S'
也没有输入'P'
的情况。程序总是评估第三种情况(既不是'S'
也不是'P'),为什么这样呢?比较从标准输入读取的字符输入
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
float calc_resistance(char conn) {
float retval = 0.0;
if (conn == 'S') {
retval = 1;
}
else if (conn == 'P') {
retval = 2;
}
else {
retval = -1;
}
return retval;
}
int main() {
char connection_type[25];
float resistance = 0.0;
while(1) {
printf("Enter 'S' or 'P': ");
scanf("%s", connection_type);
if(strlen(connection_type) != 1 ||
(strncmp(connection_type,"S",25) && strncmp(connection_type,"P",25))) {
printf("Answer not understood. Enter 'S' or 'P'.\n");
continue;
}
break;
}
resistance = calc_resistance(connection_type);
printf("Connection type: %f", resistance);
}