gpt4 book ai didi

c - 将数组中的数字转换为整数。 (和更多)

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

我是 C 新手,正在尝试构建一个仅使用以下内容的程序:

  • 数组,
  • 循环,
  • 如果-否则,
  • 基本功能(打印、扫描)
  • 没有字符串之类的!

我的要求:

  • 我应该在一行中从用户那里得到一个方程。 “=”结束等式。
  • 必须恰好有两个数字
  • 必须只有一个运算符

输入示例:

589*919=

我需要将方程插入到数组中。每个数字或运算符位于数组中的另一个位置。

数组示例:

chars array: | 5 | 8 | 9 | * | 9 | 1 | 9 |

然后我需要将数组中的数字转换为两个整数,并计算方程的答案。

如何将数组中的数字变成两个整数?

到目前为止我的代码:

#include <stdio.h>
#include <stdlib.h>
#pragma warning (disable: 4996)
#define SIZE 122

void main()
{
int count = 0;
int i;
char input;
char equation[SIZE];
char key = 0;
int oprIndex;

printf("Insert equation:\n");
scanf("%c", &input);

for (i = 0; i<SIZE && input != '='; i++) //fill the array with the equation
{
equation[i] = input;
scanf("%c", &input);
count++;
}

//searching for which operater user inserted
key = '+';
for (i = 0; i < count && equation[i] != key; i++);
if (equation[i] == key)
{
printf("key: %c\n", key);
oprIndex = i;
printf("index: %d\n", oprIndex);
}

key = '-';
for (i = 0; i < count && equation[i] != key; i++);
if (equation[i] == key)
{
printf("key: %c\n", key);
oprIndex = i;
printf("index: %d\n", oprIndex);
}

key = '*';
for (i = 0; i < count && equation[i] != key; i++);
if (equation[i] == key)
{
printf("key: %c\n", key);
oprIndex = i;
printf("index: %d\n", oprIndex);
}

key = '/';
for (i = 0; i < count && equation[i] != key; i++);
if (equation[i] == key)
{
printf("key: %c\n", key);
oprIndex = i;
printf("index: %d\n", oprIndex);
}
//end of searching

for (i = 0; i < count; i++) //print the equation
{
printf("%c", equation[i]);
}
printf("=");
printf("\n");

system("pause");
}

最佳答案

只需使用带有 +* 的 for 语句即可。

如果您不知道如何将字符转换为对应的数字,请使用-'0'

例如,'5'-'0' 将为您提供 5,整数值。

编辑:

我为您添加一些示例。

int main(void) // use return value of int, not void
{
... // After you get oprIndex.

// Declare
// int opA, opB;
// first.

opA = 0;
for (i = 0; i < oprIndex; i++)
{
opA *= 10;
opA += equation[i] - '0';
}

opB = 0;
for (i = oprIndex + 1; i < count; i++)
{
opB *= 10;
opB += equation[i] - '0';
}

... // Do calcuation.

return 0; // Use return 0; at the last line of the main function.
// For C++, this is added implicitly,
// but in C, implicit adding is not in standard.
}

但是,在您的代码中,存在一些语义错误
(例如,

key = '+';
for (i = 0; i < count && equation[i] != key; i++);
if (equation[i] == key)

当您的 count 等于 SIZE 并且等式中没有 + 时,会产生段错误。),
因此,重构您的逻辑和代码以正确执行。

关于c - 将数组中的数字转换为整数。 (和更多),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41049134/

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