我正在尝试使用switch语句在三角形棱柱或三角形金字塔之间进行选择。当我选择1时,它告诉我值必须介于1和2之间。当我选择2时,它选择三角形金字塔并且似乎有效。
#include <stdio.h>
#include <stdlib.h>
int main()
{
float tt, menu1, opt1, opt2, opt3, t, opt4;
int td;
printf("Enter: ");
scanf("%f",&tt);
{
printf("\nWhat geometrical figure would you like to use for Volume?\n\n");
printf("1) Triangular Prism\n");
printf("2) Triangular Pyramid\n");
printf("User choice: ");
scanf("%f", &td);
while (td < 1 || td > 2) {
printf("\nUser choice must be between 1 and 2!\n\n");
printf("\nWhat geometrical figure would you like to use for Volume?\n\n");
printf("1) Triangular Prism\n");
printf("2) Triangular Pyramid\n");
printf("User choice: ");
scanf("%d", &td);
}
switch(td) {
case 1:
printf("Enter a, b, c, and h of the triangular prism in meters\n\n");
printf("a ");
scanf("%f", &opt1);
printf("b ");
scanf("%f", &opt2);
printf("c ");
scanf("%f", &opt3);
printf("h ");
scanf("%f", &opt4);
printf("\nWould you like to make another Volume calculation (1 for Yes, 2 for No)?");
scanf("%f", &menu1);
if (menu1 == 2) {
t = 0;
break;
}
if (menu1 < 1 || menu1 > 2) {
printf("\n\nUser choice must be between 1 and 2!\n\n");
printf("Would you like to make another Volume calculation (1 for Yes, 2 for No)?");
scanf("%f", &menu1);
}
case 2:
printf("Enter a and h of the triangular pyramid\n\n");
printf("a ");
scanf("%f", &opt1);
printf("h ");
scanf("%f", &opt2);
printf("\nWould you like to make another Volume calculation (1 for Yes, 2 for No)?");
scanf("%f", &menu1);
if (menu1 == 2) {
t = 0;
break;
}
if (menu1 < 1 || menu1 > 2) {
printf("\n\nUser choice must be between 1 and 2!\n\n");
printf("Would you like to make another Volume calculation (1 for Yes, 2 for No)?");
scanf("%f", &menu1);
}
}
}
if (tt == 4) {
printf("Enter the radius of the circle\n\n");
printf("Radius: ");
scanf("%f", &opt1);
printf("\nWould you like to make another Volume calculation (1 for Yes, 2 for No)?");
scanf("%f", &menu1);
if (menu1 == 2) {
t = 0;
}
if (menu1 < 1 || menu1 > 2) {
printf("\n\nUser choice must be between 1 and 2!\n\n");
printf("Would you like to make another Volume calculation (1 for Yes, 2 for No)?");
scanf("%f", &menu1);
}
}
}
答案 0 :(得分:1)
您必须非常小心:"%f"
中的格式代码必须与您提供的地址类型相匹配,作为附加参数:
"%d"
适用于像opt1,opt2等浮动... sizeof(float)
如果存在不匹配,则不仅不会在您的变量中获得正确的值(因为1的浮点编码与整数1不同),但您还可能存在缓冲区溢出和内存损坏的风险(如果sizeof(int)
大于gameStats = results as! [NSManagedObject]
)。