我做了三个不同的功能。我正在尝试让用户选择要操作的功能。为此,我正在尝试使用switch语句。用户输入两个数字,然后选择要对这些数字进行操作的功能。这是我的当前代码,无法正常工作。 函数MultbyTwo,isFirstBigger和addVat。
#include <stdio.h>
int multbyTwo (int a){
return a*2;
}
int isFirstBigger (int a, int b){
if (a<b){
printf("1");
}
else {
printf("0");
}
}
float addVat(float a, float 20){
return (a/100)*20;
}
int main(){
int a,b;
int choice;
printf("Which Function [0:multbyTwo,1:isFirstBigger,2:addVat]:");
scanf("%d",&choice);
printf("a:\n");
scanf("%f",&a);
printf("b:\n");
scanf("%f",&b);
switch (choice){
case 0: printf(multbyTwo(a));
break;
case 1: printf(isFirstBigger(a,b));
break;
case 2: printf(addVat(a));
break;
}
}
答案 0 :(得分:0)
除了我在评论中提到的问题之外,您的printf
调用中还缺少格式字符串。这是您的代码的有效版本,无论我更改了什么地方,都添加了“ ///”注释:
#include <stdio.h>
int multbyTwo(int a) {
return a * 2;
}
int isFirstBigger(int a, int b) {
if (a < b) {
// printf("%s", "1"); /// You print the result in main!
return 1; /// You MUST return a value!
}
else {
// printf("%s", "0"); /// You print the result in main!
return 0; /// You MUST return a value!
}
}
float addVat(float a, float vat) { /// Change here to allow a value of vat to be passed
return (a / 100) * vat; /// ... and here to use the passed value (not fixed)
}
int main() {
int a, b;
int choice;
printf("Which Function [0:multbyTwo,1:isFirstBigger,2:addVat]:");
scanf("%d", &choice);
printf("a:\n");
scanf("%d", &a); /// Use %d for integers - %f is for float types
printf("b:\n");
scanf("%d", &b); /// Use %d for integers - %f is for float types
switch (choice) { /// each call to printf MUST have the format string as the first argument...
case 0: printf("%d", multbyTwo(a));///
break;
case 1: printf("%d", isFirstBigger(a, b));///
break;
case 2: printf("%f", addVat((float)a, 20));/// Now, we must pass the value of "vat" to use in "addVat()"
break;
}
return 0; /// It's good practice to always have this explicit "return 0" in main!
}
希望对您有所帮助! (但是我不得不说,还有很多改进的空间。)
随时要求进一步的澄清和/或解释。