简体   繁体   English

为什么我的程序的output 0.000000 应该是我在提示时输入的值。 下面是代码

[英]why is the output of my program 0.000000 when it should be the value i entered when prompted. below is the code

I am trying to execute this code.我正在尝试执行此代码。 but the number variable isn't storing the value I input,what could be posssible explanations of this behaviour.但是数字变量没有存储我输入的值,这可能是对这种行为的可能解释。

#include <stdio.h>
int main(){
    float number;
    
    printf("enter a value\n");
    scanf("%5.3f",&number);
    printf("u entered : %f",number);

    return 0;
}

and below is sample of its execution以下是其执行示例

enter a value
78.467  
u entered : 0.000000

Why isn't number storing the value 78.467为什么数字不存储值 78.467

  • %5.3f is not a valid scanf format. %5.3f不是有效的scanf格式。 It should be %f .它应该是%f
  • You also do not check that scanf succeeds.您也不会检查scanf是否成功。 Always do.总是做。

Example:例子:

#include <stdio.h>
int main() {
    float number;

    puts("enter a value");
    if(scanf("%f", &number) == 1) {          // check that it succeeds
        printf("u entered : %5.3f", number); // in printf %5.3f is ok
    } else {
        puts("Erroneous input");
    }
}

"%5.3f" in scanf("%5.3f",&number); "%5.3f" in scanf("%5.3f",&number); is an invalid format so the result is undefined behavior (UB).是无效格式,因此结果是未定义的行为 (UB)。

The "5" is OK. "5"没问题。 It limits the number of characters read in the conversion to at most 5.它将转换中读取的字符数限制为最多 5 个。

".3" is not part of a valid conversion specification. ".3"不是有效转换规范的一部分。

Save time, enable all warnings.节省时间,启用所有警告。 @David Ranieri @大卫·拉涅利

// scanf("%5.3f",&number);
if (scanf("%f",&number) != 1) {
  fprintf(stderr, "Non-numeric input\n");
  return -1; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我的C程序在这里打印0.000000? - Why is my C program printing 0.000000 here? 我的程序没有 output 我输入的第一个值在我的数组中搜索。 为什么? - My program doesn't output the first value I entered to search in my array. Why? 为什么我输入错误的数据类型时我的c程序不会崩溃 - why my c program doesn't crash when i entered the wrong data type 为什么printf(“ value:%f”,10/2); 输出0.000000? - Why does printf(“value: %f”,10/2); output 0.000000? 下面的代码可以很好地运行加密部分,但是当输入“z”时,它给出了意外的输出并且不运行解密部分 - The below code runs encryption part well but when 'z' is entered it gives unexpected output and doesnt run decryption part 当变量类型不同时,为什么下面的代码给出不同的输出? - Why the below code is giving different output when variable type is different? 当我管道输出时,为什么我的分叉程序的输出不同? - Why is the output of my forking program different when I pipe its output? 为什么这个 c 程序在输入 0 时没有结束? - Why does this c program not end when entered 0? 我写了一个程序,它应该在输入“n”或“N”时终止,但它不起作用 - I wrote a program which should terminate when 'n' or 'N' is entered but it doesn't work 为什么调试时程序崩溃? - Why is my program crashing when I debug?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM