关于使用%.3f打印某个数字的基本C语言任务



我刚开始在学校学习编程,我已经很迷茫了。任务如下:

在一个单独的文件中回答所有3项任务并返回。如果printf函数的格式字符串(控制字符)为%.3f,而要打印的数字为456.876543210.17023443.14159

我该怎么做?我的代码是这样的,但它显然是错误的。

#include <stdio.h>
int main() {
int num1, num2, num3;
printf("Give a number 1n");
scanf("%i", &num1);
printf("Answer is on %.3f", &num1);
return 0;
}

它给了我0的答案,或者0.000的答案。只有0。

我真的不知道该怎么办,我的老师已经在上另一门课了,没有时间帮我太多。

此源代码:

#include <stdio.h>

int main(void)
{
printf("%.3fn", 456.87654321);
printf("%.3fn", 0.17023);
printf("%.3fn", 443.14159);
}

产生以下输出:

456.8770.170443.142

您将num1声明为int(整数…仅限整数)。

然后你从键盘上读出那个数字
我猜你正在进入456.87654321
(提示,即不是一个整数。它不适合int)

然后你试着用打印出来

printf("Answer is on %.3f", &num1);

这有几个问题。

  • %.3f用于打印doubles,而不是int
  • 你通过了";地址";(&符号)
    直接传递变量即可

修复您的代码,我得到:

#include <stdio.h>
int main() {
double num1;                       // Declare DOUBLE, not INT
printf("Give a number 1n");
scanf("%f", &num1);                // Get a DOUBLE from input, not an INT
printf("Answer is on %.3f", num1); // Remove the & (address)
return 0;
}

相关内容

最新更新