所以我是 C 的新手,我主要用它来制作概率计算器之类的东西。我当前的项目发现了2个值的增加和减少。
代码是:
#include <stdio.h>
//Variables
//Main Area
int
main ()
{
float num1;
float num2;
float num3;
float num4;
float answer;
//Scanning for the first number
printf ("\n Please Enter the first Value : ");
scanf ("%f", &num1);
//scanning for the second number
printf ("\n Please Enter the second Value : ");
scanf ("%f", &num2);
//calculating
num3 = num1 - num2;
num4 = num3 / num1;
answer = num4 * 100;
//Checking if the answer is an increase or decrease
if (answer > 0) {
printf("The answer has been decreasedby: %f\n", answer);
printf("percent");
}
else {
printf("The answer has been increased by: %f\n", answer * -1);
printf("percent");
}
//Printing the answer
}
输出:
Please Enter the first Value: 9
Please Enter the second Value : 90
The answer has been increased and the final value is: 900.000000
percent
所以我将所有值设置为
Floats
而不是Ints
,因为Ints
只支持整数。但是,当我确实得到一个整数而不是仅显示没有小数点的单个数字时,它会生成一个带有该数字和小数点后一堆零的数字。有没有办法检测数字是否是整数并只显示该数字?
谢谢
有没有办法可以检测答案是否为整数并只显示该数字?
要检测
float
是否为整数,请使用 modff()
将 float
分解为整数部分和小数部分。
float f;
float ipart;
float fpart = modff(f, &ipart);
printf("%g is %s whole number.\n", f, fpart == 0.0 ? "a" : "not a");
检测“完整性”的替代方法是使用
"%g"
以减少输出的方式打印浮点数。但这还不够,除非 "%g"
使用更高的精度 - 见下文。
printf("%g\n", 2.0/3.0); // 0.666667
printf("%g\n", 1234.0); // 1234
也许更进一步
"%g"
。使用足够宽的 precision 来显示 .
右侧的任何非零数字,并让说明符在答案为整数时去掉尾随的零。
printf("%.*g\n", FLT_DECIMAL_DIG, some_float);
printf("%.*g\n", DBL_DECIMAL_DIG, some_double);
将
answer
与 f.e. 的返回值进行比较floorf()
函数(标题math.h
) - floorf()
,因为您处理类型为float
的变量 - answer
作为参数传递。
通过这样做,您可以证明
answer
是否包含偶数十进制值。
对于输出本身,使用精度说明符(例如
.0
)指定小数部分中的位数,并将其放置在 %
和 f
转换说明符之间,例如 %.0f
。
.0
的精度指定您不希望显示小数部分。
// Checking if the answer is an increase or decrease
if ( answer > 0 ) {
if ( answer == floorf(answer) ) // If answer contains a decimal value.
printf("The answer has been decreased and the final value is: %.0f\n", answer);
else
printf("The answer has been decreased and the final value is: %.3f\n", answer);
}
else {
if ( answer == floorf(answer) ) // If answer contains a decimal value.
printf("The answer has been increased and the final value is: %.0f\n", answer * -1);
else
printf("The answer has been increased and the final value is: %.3f\n", answer * -1);
}
旁注:
我的检查方式包括:
if(num1 == (int)num1) // This checks whether num1 is integer
{
//Do something
}
else
{
//num1 is float
}