gpt4 book ai didi

c - scanf ("%f", &weight) 和 scanf ("%f", Weight) 如何确定何时添加前缀 &

转载 作者:行者123 更新时间:2023-11-30 18:23:37 29 4
gpt4 key购买 nike

我阅读了以下代码:

//talkback.c -- nosy, informative program
#include <stdio.h>
#include <string.h> //for strlen() prototype
#define DENSITY 62.4 //human density in lbs per cu ft

int main() {

float weight, volume;
int size, letters;
char name[40]; //name is an array of 40 characters

printf("Hi! What's your first name?\n");
scanf("%s", name);
printf("%s, what's your weight in pounds?\n", name);
scanf("%f", &weight);
size = sizeof name;
letters = strlen(name);
volume = weight / DENSITY;
printf("Well, %s, your volumn is %2.2f cubit feet.\n", name, volume);
printf("Also, your first name has %d letters, \n", letters);
printf("and we have %d bytes to store it.\n", size);

}

运行并输出:

In [13]: !./a.out
Hi! What's your first name?
Hery
Hery, what's your weight in pounds?
100
Well, Hery, your volumn is 1.60 cubit feet.
Also, your first name has 4 letters,
and we have 40 bytes to store it.

我注意到 scanf("%s", name);scanf("%f", &weight); ,第二个在前面有一个前缀 &重量。

如何区分哪种情况需要加前缀?

最佳答案

scanf() 代表扫描格式化字符串。现在,在从标准输入流扫描输入时,scanf() 需要将该输入数据放入某处。为了存储格式化的输入数据scanf()需要知道相同数据类型的变量的内存位置。这就是为什么 scanf() 需要一个指针(C 中的指针存储变量或表达式的内存位置)来存储输入。变量前面的地址运算符 (&),即&var 指示变量“var”的内存位置。

int var;
scanf("%d",&var);

char str[20];
scanf("%s",str);

对于第二个示例,我们不需要取址运算符,因为C 将数组名称变量视为指针

printf()scanf() 的逆函数。它将格式化的字符串打印到标准输出。 Printf 不需要任何内存位置来打印输出,它只需要变量来获取数据并根据格式说明符对其进行格式化。

printf("%c in ASCII is %d",65,65);

The output will be: A in ASCII is 65

关于c - scanf ("%f", &weight) 和 scanf ("%f", Weight) 如何确定何时添加前缀 &,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52828608/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com