gpt4 book ai didi

c - 每个数字的输出都一样吗?

转载 作者:太空宇宙 更新时间:2023-11-04 01:51:24 25 4
gpt4 key购买 nike

这个程序应该要求用户输入一个正整数(整数可以是整数类型范围内的任意位数)并用该数字加上 6 模 10 的总和替换每个数字。然后程序应该在显示输出之前交换第一个数字和最后一个数字。

示例输入/输出:

Enter the number of digits of the number: 5
Enter the number: 92828
Output: 48485

由于我的代码的某些原因,无论我输入什么数字,结果都是 6。(所以如果我输入 5 个数字,我得到 666666)。我是指针的新手,所以这有问题吗,或者我只是有一些数学错误?该程序运行时没有任何编译器警告。

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

void replace(int *a, int *b, int n);
void swap(int *p, int *q);

int main()
{
int n = 0;
int i = 0;
int a[100], b[100];

//Prompt user to enter number of digits
printf("Enter the number of digits you'd like to replace: ");
scanf("%d", &n);

//Prompt user to enter the number to use
printf("Enter the number to use: ");

for(i = 0; i < n; i++);
scanf("%1d", &a[i]);

//replace function
replace(a, b, n);

for(i = 0; i < n; i++)
printf("%d", b[i]);
printf("\n\n");
return 0;
}

void replace(int *a, int *b, int n)
{
int i;
for (i = 0; i < n; i++)
{
*(b+i) = (*(a+i)+ 6) % 10;
}
printf("The output is: ");

//swap function
swap(b, (b+ (n-1)));
}

void swap(int *p, int *q)
{
int t;
t = *p;
*p = *q;
*q = t;
}

最佳答案

除了以下代码片段中的一个愚蠢错误外,您的代码绝对正确。

for(i = 0; i < n; i++);
scanf("%1d", &a[i]);

为什么要在 for 语句之后放一个 ;?这意味着您的 for 循环仅迭代一次(如果 n = 5,则不是 5 次)。因此,只有第一个数字输入被认为是由用户给出的,但也存储在 a[5] 中(考虑到 n = 5),值存储在 a[0]a[4]都是垃圾值。

只需删除分号并按如下方式更新您的代码。

for(i = 0; i < n; i++)
scanf("%1d", &a[i]);

现在它工作正常。

关于c - 每个数字的输出都一样吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42331442/

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