【问题标题】:Factoring Pointer Error in C programming在 C 编程中分解指针错误
【发布时间】:2015-03-20 14:17:24
【问题描述】:

所以我在制作一个要求用户输入数字然后使用该数字的程序时遇到了麻烦,我必须将指针的值增加到 two_count 和 three_count。这些与输入的数字中的二和三的因子相反。

例如,如果用户输入 2,那么程序应该吐出 “有 1 个 2 因子和 0 个 3 因子” 然后用户可以输入0退出程序

到目前为止我所拥有的是

include <stdio.h>
void main()
{
    int* two_count;
    int* three_count;
    int num;

    while(two_count >= 0 || three_count >= 0)
    {
        printf("Enter a number: \n");
        scanf("%d", &num);

        if(num % 2)
        {
            two_count++;
        }
        else if(num % 3)
        {
            three_count++;
        }
        else if(num == 0)
        {
            printf("Thank you for playing, enjoy your day!\n");
            break;
        }

        printf("So far, there have been %d factors of 2 and %d factors of   3\n", two_count, three_count);
    }

}

谢谢!

【问题讨论】:

  • 为什么将这两个计数器声明为 int 指针而不是 int 变量?
  • 程序需要指针,我该怎么做?
  • 它们必须链接到指针来保存计数。

标签: c pointers factors


【解决方案1】:

如果你想使用指针,你可以这样做

int two_count = 0;
int* two_count_ptr = &two_count;
int three_count = 0;
int* three_count_ptr = &three_count;

然后,为了检索值和递增,您需要取消引用指针

while(*two_count_ptr >= 0 || *three_count_ptr >= 0)

(*two_count_ptr)++;

希望这会有所帮助。

【讨论】:

  • 你好,我只是想刚才关于指针的说法,为什么我们需要它们,我想我们必须在程序中使用另一个方法调用。 void update_counts(int value, int* two_count, int* three_count);
  • 我明白了,这更有意义。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-18
  • 2016-02-24
  • 1970-01-01
  • 2021-05-25
  • 2012-04-10
  • 1970-01-01
  • 2013-10-09
相关资源
最近更新 更多