[英]Error When Inputting Data to Be Written to File
所以我正在嘗試編寫一個程序,允許您輸入電路的電壓和電阻,然后計算出電路的電流並將其寫入.txt
文件。 這是代碼:
void main()
{
float V=0;
float R=0;
float I=0;
printf("Enter your voltage value...\n");
scanf("%f&V", V);
printf("Enter your resistance value...\n");
scanf("%f&R", R);
I = V / R;
FILE *f = fopen("C:/Users/Joe/Desktop/file.txt", "w");
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
else
{
fprintf(f, "%f %f %f\n", V, R, I);
}
fclose(f);
}
但是,當我輸入數據時,出現以下錯誤:
“第一個 project.exe 中 0x566B96AA (msvcr120d.dll) 處的未處理異常:0xC0000005:訪問沖突寫入位置 0x00000000。”
有誰知道這意味着什么以及我該如何解決?
就像 Raghu 在評論中所說,你需要改變scanf("%f&V", V);
至scanf("%f", &V);
scanf("%f&R", R);
也是如此
改為scanf("%f", &R);
這里要提兩件事。
scanf()
一起提供的格式字符串應與確切的輸入匹配。所以,基本上。 你的輸入命令應該是
scanf("%f", &V);
和
scanf("%f", &R);
代替
scanf("%f&R", R);
和
scanf("%f&V", V);
也就是說,
scanf()
和函數族的返回值。void main()
不太正確。 您應該使用int main(void)
代替。您應該在scanf
的第二個參數中傳遞變量的地址。
#include <stdio.h>
#include <stdlib.h>
int main()
{
float V=0;
float R=0;
float I=0;
printf("Enter your voltage value:");
scanf("%f",&V);
printf("\nEnter your resistance value:");
scanf("%f", &R);
I = V / R;
FILE *f = fopen("C:/Users/Joe/Desktop/file.txt", "w");
if (f == NULL)
{
printf("\nError opening file!\n");
exit(1);
}
else
{
fprintf(f, "%f %f %f\n", V, R, I);
}
fclose(f);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.