我是 C 新手,我真的不知道我做错了什么。
我遇到的问题是我应该使用 scanf 向用户询问 3 个问题。我应该要求用户提供一个整数、一个正实数和一个非负数,然后使用 %.2f
将这些数字计算为 XX.XX
。/p>
//pre-processor directives
#include <stdio.h>
#include <math.h>
//main function
int main()
{
//declare variables
int smp1,smp2, smp3,total;
printf("sample 1?\n"); // positive integer
scanf("%d", &smp1);
printf("sample 2?\n"); //positive real number
scanf("%f",&smp2);
printf("sample 3?\n"); // non negative number
scanf("%u", &smp3);
total = (smp1 + smp2 / smp3);
printf("The final result is %.2f",total);
//end of main
return 0;
}
无论我在那里输入什么,结果最终都是0.00
。它甚至不会做简单的加法,我也不知道为什么。
最佳答案
您的主要问题是您将所有变量声明为int
,但smp2
和total
必须保存浮点值。
将您的声明更改为
int smp1;
double smp2, total;
unsigned int smp3;
这样,变量的类型就与 printf
和 scanf
调用中使用的转换说明符相匹配。
类型在 C 中很重要,每个 printf
和 scanf
调用中的参数类型是否与转换说明符匹配取决于您。
检查编译器文档,了解如何启用警告(更好的是,将所有警告视为错误)。大多数编译器应该警告像这样的类型不匹配,但有时您必须设置一个标志才能显示这些警告。
关于c - 无法用C计算。你如何用C计算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50684841/