gpt4 book ai didi

c - 为什么atof功能不能正常工作?

转载 作者:行者123 更新时间:2023-11-30 16:19:00 25 4
gpt4 key购买 nike

我在大学类(class)中用 C 语言编码,我们有一个项目从用户那里获取方程并给出矩阵等的解决方案......我的问题是,我正在尝试使用 atof() 函数,但由于某种原因,一旦它工作,我就无法在同一个循环中找到它,而其他时候却不起作用。

我已经尝试过其他函数来替换 atof,例如 strtod,但效果不佳。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cstdbool>

void main()
{
int num, check = 0,i,j,k=0,len1=0;
char equ[80],tempx[20],tempy[20], tempz[20], tempd[20];
double *x, *y, *z, *d;
printf_s("Number of equations (1-3): ");
scanf_s("%d", &num);
getchar();
while (check == 0) //a check to see if we got a number between 1-3.
{
if (num > 0 && num < 4)
check = 1;
else
{
printf_s("Please enter a number between 1-3.\n");
printf_s("Number of equations (1-3): ");
scanf_s("%d", &num);
}
}
x = malloc(sizeof(double)*num);
if (!x) exit(1);
y = malloc(sizeof(double)*num);
if (!y) exit(1);
z = malloc(sizeof(double)*num);
if (!z) exit(1);
d = malloc(sizeof(double)*num);
if (!d) exit(1);
for (i = 0; i < num; i++) //getting the equations and putting them into the matrix
{
printf_s("Enter equation %d: ", i + 1);
gets_s(equ, sizeof(equ));
len1 = strlen(equ);

for (j = 0; j <len1 ; j++)
{
if (equ[j] == 'x')
{
k = 0;
while ((equ[j-k] != '+' || equ[j-k] != '-') && j-k>=0)
{
tempx[j-k] = equ[j-k];
k++;
}
x[i] = atof(tempx);
}
else if (equ[j] == 'y')
{
k = 0;
while ((equ[j-k] != '+' || equ[j-k] != '-') && j - k >= 0)
{
tempy[j-k] = equ[j-k];
k++;
}
y[i] = atof(tempy);
}
else if (equ[j] == 'z')
{
k = 0;
while ((equ[j - k] != '+' || equ[j - k] != '-') && j - k >= 0)
{
tempz[j-k] = equ[j - k];
k++;
}
z[i] = atof(tempz);
}
else if (equ[j] == '=')
{
k = 0;
while (equ[j+k])
{
tempd[k] = equ[j + k];
k++;
}
d[i] = atof(tempd);
}
}
}
free(x);
free(y);
free(z);
free(d);
}

我希望在 d[i] 中得到与在 x[i] 中相同的结果,但每次我尝试打印 d[i] ] 我得到 0.0000。当我在 atof 内的 tempd 上尝试函数 _strrev 时,我在 d[i] 内得到了相反的结果。

最佳答案

所以问题是在最后一个循环中我插入了一个以“=”开头的字符串而不是数字。显然,当第一个字符不是数字时,atof() 不起作用。

关于c - 为什么atof功能不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55751635/

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